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.70 msec * (1 + ilog(ncpus)), units: nanoseconds)
78 */
79 unsigned int sysctl_sched_base_slice = 700000ULL;
80 static unsigned int normalized_sysctl_sched_base_slice = 700000ULL;
81
82 __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL;
83
setup_sched_thermal_decay_shift(char * str)84 static int __init setup_sched_thermal_decay_shift(char *str)
85 {
86 pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n");
87 return 1;
88 }
89 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
90
91 /*
92 * For asym packing, by default the lower numbered CPU has higher priority.
93 */
arch_asym_cpu_priority(int cpu)94 int __weak arch_asym_cpu_priority(int cpu)
95 {
96 return -cpu;
97 }
98
99 /*
100 * The margin used when comparing utilization with CPU capacity.
101 *
102 * (default: ~20%)
103 */
104 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
105
106 /*
107 * The margin used when comparing CPU capacities.
108 * is 'cap1' noticeably greater than 'cap2'
109 *
110 * (default: ~5%)
111 */
112 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
113
114 #ifdef CONFIG_CFS_BANDWIDTH
115 /*
116 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
117 * each time a cfs_rq requests quota.
118 *
119 * Note: in the case that the slice exceeds the runtime remaining (either due
120 * to consumption or the quota being specified to be smaller than the slice)
121 * we will always only issue the remaining available time.
122 *
123 * (default: 5 msec, units: microseconds)
124 */
125 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
126 #endif
127
128 #ifdef CONFIG_NUMA_BALANCING
129 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
130 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
131 #endif
132
133 #ifdef CONFIG_SYSCTL
134 static const struct ctl_table sched_fair_sysctls[] = {
135 #ifdef CONFIG_CFS_BANDWIDTH
136 {
137 .procname = "sched_cfs_bandwidth_slice_us",
138 .data = &sysctl_sched_cfs_bandwidth_slice,
139 .maxlen = sizeof(unsigned int),
140 .mode = 0644,
141 .proc_handler = proc_dointvec_minmax,
142 .extra1 = SYSCTL_ONE,
143 },
144 #endif
145 #ifdef CONFIG_NUMA_BALANCING
146 {
147 .procname = "numa_balancing_promote_rate_limit_MBps",
148 .data = &sysctl_numa_balancing_promote_rate_limit,
149 .maxlen = sizeof(unsigned int),
150 .mode = 0644,
151 .proc_handler = proc_dointvec_minmax,
152 .extra1 = SYSCTL_ZERO,
153 },
154 #endif /* CONFIG_NUMA_BALANCING */
155 };
156
sched_fair_sysctl_init(void)157 static int __init sched_fair_sysctl_init(void)
158 {
159 register_sysctl_init("kernel", sched_fair_sysctls);
160 return 0;
161 }
162 late_initcall(sched_fair_sysctl_init);
163 #endif /* CONFIG_SYSCTL */
164
update_load_add(struct load_weight * lw,unsigned long inc)165 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
166 {
167 lw->weight += inc;
168 lw->inv_weight = 0;
169 }
170
update_load_sub(struct load_weight * lw,unsigned long dec)171 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
172 {
173 lw->weight -= dec;
174 lw->inv_weight = 0;
175 }
176
update_load_set(struct load_weight * lw,unsigned long w)177 static inline void update_load_set(struct load_weight *lw, unsigned long w)
178 {
179 lw->weight = w;
180 lw->inv_weight = 0;
181 }
182
183 /*
184 * Increase the granularity value when there are more CPUs,
185 * because with more CPUs the 'effective latency' as visible
186 * to users decreases. But the relationship is not linear,
187 * so pick a second-best guess by going with the log2 of the
188 * number of CPUs.
189 *
190 * This idea comes from the SD scheduler of Con Kolivas:
191 */
get_update_sysctl_factor(void)192 static unsigned int get_update_sysctl_factor(void)
193 {
194 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
195 unsigned int factor;
196
197 switch (sysctl_sched_tunable_scaling) {
198 case SCHED_TUNABLESCALING_NONE:
199 factor = 1;
200 break;
201 case SCHED_TUNABLESCALING_LINEAR:
202 factor = cpus;
203 break;
204 case SCHED_TUNABLESCALING_LOG:
205 default:
206 factor = 1 + ilog2(cpus);
207 break;
208 }
209
210 return factor;
211 }
212
update_sysctl(void)213 static void update_sysctl(void)
214 {
215 unsigned int factor = get_update_sysctl_factor();
216
217 #define SET_SYSCTL(name) \
218 (sysctl_##name = (factor) * normalized_sysctl_##name)
219 SET_SYSCTL(sched_base_slice);
220 #undef SET_SYSCTL
221 }
222
sched_init_granularity(void)223 void __init sched_init_granularity(void)
224 {
225 update_sysctl();
226 }
227
228 #define WMULT_CONST (~0U)
229 #define WMULT_SHIFT 32
230
__update_inv_weight(struct load_weight * lw)231 static void __update_inv_weight(struct load_weight *lw)
232 {
233 unsigned long w;
234
235 if (likely(lw->inv_weight))
236 return;
237
238 w = scale_load_down(lw->weight);
239
240 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
241 lw->inv_weight = 1;
242 else if (unlikely(!w))
243 lw->inv_weight = WMULT_CONST;
244 else
245 lw->inv_weight = WMULT_CONST / w;
246 }
247
248 /*
249 * delta_exec * weight / lw.weight
250 * OR
251 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
252 *
253 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
254 * we're guaranteed shift stays positive because inv_weight is guaranteed to
255 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
256 *
257 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
258 * weight/lw.weight <= 1, and therefore our shift will also be positive.
259 */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)260 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
261 {
262 u64 fact = scale_load_down(weight);
263 u32 fact_hi = (u32)(fact >> 32);
264 int shift = WMULT_SHIFT;
265 int fs;
266
267 __update_inv_weight(lw);
268
269 if (unlikely(fact_hi)) {
270 fs = fls(fact_hi);
271 shift -= fs;
272 fact >>= fs;
273 }
274
275 fact = mul_u32_u32(fact, lw->inv_weight);
276
277 fact_hi = (u32)(fact >> 32);
278 if (fact_hi) {
279 fs = fls(fact_hi);
280 shift -= fs;
281 fact >>= fs;
282 }
283
284 return mul_u64_u32_shr(delta_exec, fact, shift);
285 }
286
287 /*
288 * delta /= w
289 */
calc_delta_fair(u64 delta,struct sched_entity * se)290 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
291 {
292 if (unlikely(se->load.weight != NICE_0_LOAD))
293 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
294
295 return delta;
296 }
297
298 const struct sched_class fair_sched_class;
299
300 /**************************************************************
301 * CFS operations on generic schedulable entities:
302 */
303
304 #ifdef CONFIG_FAIR_GROUP_SCHED
305
306 /* Walk up scheduling entities hierarchy */
307 #define for_each_sched_entity(se) \
308 for (; se; se = se->parent)
309
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)310 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
311 {
312 struct rq *rq = rq_of(cfs_rq);
313 int cpu = cpu_of(rq);
314
315 if (cfs_rq->on_list)
316 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
317
318 cfs_rq->on_list = 1;
319
320 /*
321 * Ensure we either appear before our parent (if already
322 * enqueued) or force our parent to appear after us when it is
323 * enqueued. The fact that we always enqueue bottom-up
324 * reduces this to two cases and a special case for the root
325 * cfs_rq. Furthermore, it also means that we will always reset
326 * tmp_alone_branch either when the branch is connected
327 * to a tree or when we reach the top of the tree
328 */
329 if (cfs_rq->tg->parent &&
330 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
331 /*
332 * If parent is already on the list, we add the child
333 * just before. Thanks to circular linked property of
334 * the list, this means to put the child at the tail
335 * of the list that starts by parent.
336 */
337 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
338 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
339 /*
340 * The branch is now connected to its tree so we can
341 * reset tmp_alone_branch to the beginning of the
342 * list.
343 */
344 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
345 return true;
346 }
347
348 if (!cfs_rq->tg->parent) {
349 /*
350 * cfs rq without parent should be put
351 * at the tail of the list.
352 */
353 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
354 &rq->leaf_cfs_rq_list);
355 /*
356 * We have reach the top of a tree so we can reset
357 * tmp_alone_branch to the beginning of the list.
358 */
359 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
360 return true;
361 }
362
363 /*
364 * The parent has not already been added so we want to
365 * make sure that it will be put after us.
366 * tmp_alone_branch points to the begin of the branch
367 * where we will add parent.
368 */
369 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
370 /*
371 * update tmp_alone_branch to points to the new begin
372 * of the branch
373 */
374 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
375 return false;
376 }
377
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)378 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
379 {
380 if (cfs_rq->on_list) {
381 struct rq *rq = rq_of(cfs_rq);
382
383 /*
384 * With cfs_rq being unthrottled/throttled during an enqueue,
385 * it can happen the tmp_alone_branch points to the leaf that
386 * we finally want to delete. In this case, tmp_alone_branch moves
387 * to the prev element but it will point to rq->leaf_cfs_rq_list
388 * at the end of the enqueue.
389 */
390 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
391 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
392
393 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
394 cfs_rq->on_list = 0;
395 }
396 }
397
assert_list_leaf_cfs_rq(struct rq * rq)398 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
399 {
400 WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
401 }
402
403 /* Iterate through all leaf cfs_rq's on a runqueue */
404 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
405 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
406 leaf_cfs_rq_list)
407
408 /* Do the two (enqueued) entities belong to the same group ? */
409 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)410 is_same_group(struct sched_entity *se, struct sched_entity *pse)
411 {
412 if (se->cfs_rq == pse->cfs_rq)
413 return se->cfs_rq;
414
415 return NULL;
416 }
417
parent_entity(const struct sched_entity * se)418 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
419 {
420 return se->parent;
421 }
422
423 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)424 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
425 {
426 int se_depth, pse_depth;
427
428 /*
429 * preemption test can be made between sibling entities who are in the
430 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
431 * both tasks until we find their ancestors who are siblings of common
432 * parent.
433 */
434
435 /* First walk up until both entities are at same depth */
436 se_depth = (*se)->depth;
437 pse_depth = (*pse)->depth;
438
439 while (se_depth > pse_depth) {
440 se_depth--;
441 *se = parent_entity(*se);
442 }
443
444 while (pse_depth > se_depth) {
445 pse_depth--;
446 *pse = parent_entity(*pse);
447 }
448
449 while (!is_same_group(*se, *pse)) {
450 *se = parent_entity(*se);
451 *pse = parent_entity(*pse);
452 }
453 }
454
tg_is_idle(struct task_group * tg)455 static int tg_is_idle(struct task_group *tg)
456 {
457 return tg->idle > 0;
458 }
459
cfs_rq_is_idle(struct cfs_rq * cfs_rq)460 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
461 {
462 return cfs_rq->idle > 0;
463 }
464
se_is_idle(struct sched_entity * se)465 static int se_is_idle(struct sched_entity *se)
466 {
467 if (entity_is_task(se))
468 return task_has_idle_policy(task_of(se));
469 return cfs_rq_is_idle(group_cfs_rq(se));
470 }
471
472 #else /* !CONFIG_FAIR_GROUP_SCHED: */
473
474 #define for_each_sched_entity(se) \
475 for (; se; se = NULL)
476
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)477 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
478 {
479 return true;
480 }
481
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)482 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
483 {
484 }
485
assert_list_leaf_cfs_rq(struct rq * rq)486 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
487 {
488 }
489
490 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
491 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
492
parent_entity(struct sched_entity * se)493 static inline struct sched_entity *parent_entity(struct sched_entity *se)
494 {
495 return NULL;
496 }
497
498 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)499 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
500 {
501 }
502
tg_is_idle(struct task_group * tg)503 static inline int tg_is_idle(struct task_group *tg)
504 {
505 return 0;
506 }
507
cfs_rq_is_idle(struct cfs_rq * cfs_rq)508 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
509 {
510 return 0;
511 }
512
se_is_idle(struct sched_entity * se)513 static int se_is_idle(struct sched_entity *se)
514 {
515 return task_has_idle_policy(task_of(se));
516 }
517
518 #endif /* !CONFIG_FAIR_GROUP_SCHED */
519
520 static __always_inline
521 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
522
523 /**************************************************************
524 * Scheduling class tree data structure manipulation methods:
525 */
526
max_vruntime(u64 max_vruntime,u64 vruntime)527 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime)
528 {
529 s64 delta = (s64)(vruntime - max_vruntime);
530 if (delta > 0)
531 max_vruntime = vruntime;
532
533 return max_vruntime;
534 }
535
min_vruntime(u64 min_vruntime,u64 vruntime)536 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime)
537 {
538 s64 delta = (s64)(vruntime - min_vruntime);
539 if (delta < 0)
540 min_vruntime = vruntime;
541
542 return min_vruntime;
543 }
544
entity_before(const struct sched_entity * a,const struct sched_entity * b)545 static inline bool entity_before(const struct sched_entity *a,
546 const struct sched_entity *b)
547 {
548 /*
549 * Tiebreak on vruntime seems unnecessary since it can
550 * hardly happen.
551 */
552 return (s64)(a->deadline - b->deadline) < 0;
553 }
554
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)555 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
556 {
557 return (s64)(se->vruntime - cfs_rq->zero_vruntime);
558 }
559
560 #define __node_2_se(node) \
561 rb_entry((node), struct sched_entity, run_node)
562
563 /*
564 * Compute virtual time from the per-task service numbers:
565 *
566 * Fair schedulers conserve lag:
567 *
568 * \Sum lag_i = 0
569 *
570 * Where lag_i is given by:
571 *
572 * lag_i = S - s_i = w_i * (V - v_i)
573 *
574 * Where S is the ideal service time and V is it's virtual time counterpart.
575 * Therefore:
576 *
577 * \Sum lag_i = 0
578 * \Sum w_i * (V - v_i) = 0
579 * \Sum w_i * V - w_i * v_i = 0
580 *
581 * From which we can solve an expression for V in v_i (which we have in
582 * se->vruntime):
583 *
584 * \Sum v_i * w_i \Sum v_i * w_i
585 * V = -------------- = --------------
586 * \Sum w_i W
587 *
588 * Specifically, this is the weighted average of all entity virtual runtimes.
589 *
590 * [[ NOTE: this is only equal to the ideal scheduler under the condition
591 * that join/leave operations happen at lag_i = 0, otherwise the
592 * virtual time has non-contiguous motion equivalent to:
593 *
594 * V +-= lag_i / W
595 *
596 * Also see the comment in place_entity() that deals with this. ]]
597 *
598 * However, since v_i is u64, and the multiplication could easily overflow
599 * transform it into a relative form that uses smaller quantities:
600 *
601 * Substitute: v_i == (v_i - v0) + v0
602 *
603 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
604 * V = ---------------------------- = --------------------- + v0
605 * W W
606 *
607 * Which we track using:
608 *
609 * v0 := cfs_rq->zero_vruntime
610 * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
611 * \Sum w_i := cfs_rq->avg_load
612 *
613 * Since zero_vruntime closely tracks the per-task service, these
614 * deltas: (v_i - v), will be in the order of the maximal (virtual) lag
615 * induced in the system due to quantisation.
616 *
617 * Also, we use scale_load_down() to reduce the size.
618 *
619 * As measured, the max (key * weight) value was ~44 bits for a kernel build.
620 */
621 static void
avg_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)622 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
623 {
624 unsigned long weight = scale_load_down(se->load.weight);
625 s64 key = entity_key(cfs_rq, se);
626
627 cfs_rq->avg_vruntime += key * weight;
628 cfs_rq->avg_load += weight;
629 }
630
631 static void
avg_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)632 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
633 {
634 unsigned long weight = scale_load_down(se->load.weight);
635 s64 key = entity_key(cfs_rq, se);
636
637 cfs_rq->avg_vruntime -= key * weight;
638 cfs_rq->avg_load -= weight;
639 }
640
641 static inline
avg_vruntime_update(struct cfs_rq * cfs_rq,s64 delta)642 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
643 {
644 /*
645 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
646 */
647 cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
648 }
649
650 /*
651 * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
652 * For this to be so, the result of this function must have a left bias.
653 */
avg_vruntime(struct cfs_rq * cfs_rq)654 u64 avg_vruntime(struct cfs_rq *cfs_rq)
655 {
656 struct sched_entity *curr = cfs_rq->curr;
657 s64 avg = cfs_rq->avg_vruntime;
658 long load = cfs_rq->avg_load;
659
660 if (curr && curr->on_rq) {
661 unsigned long weight = scale_load_down(curr->load.weight);
662
663 avg += entity_key(cfs_rq, curr) * weight;
664 load += weight;
665 }
666
667 if (load) {
668 /* sign flips effective floor / ceiling */
669 if (avg < 0)
670 avg -= (load - 1);
671 avg = div_s64(avg, load);
672 }
673
674 return cfs_rq->zero_vruntime + avg;
675 }
676
677 /*
678 * lag_i = S - s_i = w_i * (V - v_i)
679 *
680 * However, since V is approximated by the weighted average of all entities it
681 * is possible -- by addition/removal/reweight to the tree -- to move V around
682 * and end up with a larger lag than we started with.
683 *
684 * Limit this to either double the slice length with a minimum of TICK_NSEC
685 * since that is the timing granularity.
686 *
687 * EEVDF gives the following limit for a steady state system:
688 *
689 * -r_max < lag < max(r_max, q)
690 *
691 * XXX could add max_slice to the augmented data to track this.
692 */
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)693 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
694 {
695 s64 vlag, limit;
696
697 WARN_ON_ONCE(!se->on_rq);
698
699 vlag = avg_vruntime(cfs_rq) - se->vruntime;
700 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
701
702 se->vlag = clamp(vlag, -limit, limit);
703 }
704
705 /*
706 * Entity is eligible once it received less service than it ought to have,
707 * eg. lag >= 0.
708 *
709 * lag_i = S - s_i = w_i*(V - v_i)
710 *
711 * lag_i >= 0 -> V >= v_i
712 *
713 * \Sum (v_i - v)*w_i
714 * V = ------------------ + v
715 * \Sum w_i
716 *
717 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
718 *
719 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due
720 * to the loss in precision caused by the division.
721 */
vruntime_eligible(struct cfs_rq * cfs_rq,u64 vruntime)722 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime)
723 {
724 struct sched_entity *curr = cfs_rq->curr;
725 s64 avg = cfs_rq->avg_vruntime;
726 long load = cfs_rq->avg_load;
727
728 if (curr && curr->on_rq) {
729 unsigned long weight = scale_load_down(curr->load.weight);
730
731 avg += entity_key(cfs_rq, curr) * weight;
732 load += weight;
733 }
734
735 return avg >= (s64)(vruntime - cfs_rq->zero_vruntime) * load;
736 }
737
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)738 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
739 {
740 return vruntime_eligible(cfs_rq, se->vruntime);
741 }
742
update_zero_vruntime(struct cfs_rq * cfs_rq)743 static void update_zero_vruntime(struct cfs_rq *cfs_rq)
744 {
745 u64 vruntime = avg_vruntime(cfs_rq);
746 s64 delta = (s64)(vruntime - cfs_rq->zero_vruntime);
747
748 avg_vruntime_update(cfs_rq, delta);
749
750 cfs_rq->zero_vruntime = vruntime;
751 }
752
cfs_rq_min_slice(struct cfs_rq * cfs_rq)753 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq)
754 {
755 struct sched_entity *root = __pick_root_entity(cfs_rq);
756 struct sched_entity *curr = cfs_rq->curr;
757 u64 min_slice = ~0ULL;
758
759 if (curr && curr->on_rq)
760 min_slice = curr->slice;
761
762 if (root)
763 min_slice = min(min_slice, root->min_slice);
764
765 return min_slice;
766 }
767
__entity_less(struct rb_node * a,const struct rb_node * b)768 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
769 {
770 return entity_before(__node_2_se(a), __node_2_se(b));
771 }
772
773 #define vruntime_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
774
__min_vruntime_update(struct sched_entity * se,struct rb_node * node)775 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node)
776 {
777 if (node) {
778 struct sched_entity *rse = __node_2_se(node);
779 if (vruntime_gt(min_vruntime, se, rse))
780 se->min_vruntime = rse->min_vruntime;
781 }
782 }
783
__min_slice_update(struct sched_entity * se,struct rb_node * node)784 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node)
785 {
786 if (node) {
787 struct sched_entity *rse = __node_2_se(node);
788 if (rse->min_slice < se->min_slice)
789 se->min_slice = rse->min_slice;
790 }
791 }
792
793 /*
794 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime)
795 */
min_vruntime_update(struct sched_entity * se,bool exit)796 static inline bool min_vruntime_update(struct sched_entity *se, bool exit)
797 {
798 u64 old_min_vruntime = se->min_vruntime;
799 u64 old_min_slice = se->min_slice;
800 struct rb_node *node = &se->run_node;
801
802 se->min_vruntime = se->vruntime;
803 __min_vruntime_update(se, node->rb_right);
804 __min_vruntime_update(se, node->rb_left);
805
806 se->min_slice = se->slice;
807 __min_slice_update(se, node->rb_right);
808 __min_slice_update(se, node->rb_left);
809
810 return se->min_vruntime == old_min_vruntime &&
811 se->min_slice == old_min_slice;
812 }
813
814 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity,
815 run_node, min_vruntime, min_vruntime_update);
816
817 /*
818 * Enqueue an entity into the rb-tree:
819 */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)820 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
821 {
822 avg_vruntime_add(cfs_rq, se);
823 update_zero_vruntime(cfs_rq);
824 se->min_vruntime = se->vruntime;
825 se->min_slice = se->slice;
826 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
827 __entity_less, &min_vruntime_cb);
828 }
829
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)830 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
831 {
832 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
833 &min_vruntime_cb);
834 avg_vruntime_sub(cfs_rq, se);
835 update_zero_vruntime(cfs_rq);
836 }
837
__pick_root_entity(struct cfs_rq * cfs_rq)838 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq)
839 {
840 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node;
841
842 if (!root)
843 return NULL;
844
845 return __node_2_se(root);
846 }
847
__pick_first_entity(struct cfs_rq * cfs_rq)848 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
849 {
850 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
851
852 if (!left)
853 return NULL;
854
855 return __node_2_se(left);
856 }
857
858 /*
859 * Set the vruntime up to which an entity can run before looking
860 * for another entity to pick.
861 * In case of run to parity, we use the shortest slice of the enqueued
862 * entities to set the protected period.
863 * When run to parity is disabled, we give a minimum quantum to the running
864 * entity to ensure progress.
865 */
set_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)866 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
867 {
868 u64 slice = normalized_sysctl_sched_base_slice;
869 u64 vprot = se->deadline;
870
871 if (sched_feat(RUN_TO_PARITY))
872 slice = cfs_rq_min_slice(cfs_rq);
873
874 slice = min(slice, se->slice);
875 if (slice != se->slice)
876 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se));
877
878 se->vprot = vprot;
879 }
880
update_protect_slice(struct cfs_rq * cfs_rq,struct sched_entity * se)881 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
882 {
883 u64 slice = cfs_rq_min_slice(cfs_rq);
884
885 se->vprot = min_vruntime(se->vprot, se->vruntime + calc_delta_fair(slice, se));
886 }
887
protect_slice(struct sched_entity * se)888 static inline bool protect_slice(struct sched_entity *se)
889 {
890 return ((s64)(se->vprot - se->vruntime) > 0);
891 }
892
cancel_protect_slice(struct sched_entity * se)893 static inline void cancel_protect_slice(struct sched_entity *se)
894 {
895 if (protect_slice(se))
896 se->vprot = se->vruntime;
897 }
898
899 /*
900 * Earliest Eligible Virtual Deadline First
901 *
902 * In order to provide latency guarantees for different request sizes
903 * EEVDF selects the best runnable task from two criteria:
904 *
905 * 1) the task must be eligible (must be owed service)
906 *
907 * 2) from those tasks that meet 1), we select the one
908 * with the earliest virtual deadline.
909 *
910 * We can do this in O(log n) time due to an augmented RB-tree. The
911 * tree keeps the entries sorted on deadline, but also functions as a
912 * heap based on the vruntime by keeping:
913 *
914 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime)
915 *
916 * Which allows tree pruning through eligibility.
917 */
__pick_eevdf(struct cfs_rq * cfs_rq,bool protect)918 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq, bool protect)
919 {
920 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
921 struct sched_entity *se = __pick_first_entity(cfs_rq);
922 struct sched_entity *curr = cfs_rq->curr;
923 struct sched_entity *best = NULL;
924
925 /*
926 * We can safely skip eligibility check if there is only one entity
927 * in this cfs_rq, saving some cycles.
928 */
929 if (cfs_rq->nr_queued == 1)
930 return curr && curr->on_rq ? curr : se;
931
932 /*
933 * Picking the ->next buddy will affect latency but not fairness.
934 */
935 if (sched_feat(PICK_BUDDY) &&
936 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) {
937 /* ->next will never be delayed */
938 WARN_ON_ONCE(cfs_rq->next->sched_delayed);
939 return cfs_rq->next;
940 }
941
942 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
943 curr = NULL;
944
945 if (curr && protect && protect_slice(curr))
946 return curr;
947
948 /* Pick the leftmost entity if it's eligible */
949 if (se && entity_eligible(cfs_rq, se)) {
950 best = se;
951 goto found;
952 }
953
954 /* Heap search for the EEVD entity */
955 while (node) {
956 struct rb_node *left = node->rb_left;
957
958 /*
959 * Eligible entities in left subtree are always better
960 * choices, since they have earlier deadlines.
961 */
962 if (left && vruntime_eligible(cfs_rq,
963 __node_2_se(left)->min_vruntime)) {
964 node = left;
965 continue;
966 }
967
968 se = __node_2_se(node);
969
970 /*
971 * The left subtree either is empty or has no eligible
972 * entity, so check the current node since it is the one
973 * with earliest deadline that might be eligible.
974 */
975 if (entity_eligible(cfs_rq, se)) {
976 best = se;
977 break;
978 }
979
980 node = node->rb_right;
981 }
982 found:
983 if (!best || (curr && entity_before(curr, best)))
984 best = curr;
985
986 return best;
987 }
988
pick_eevdf(struct cfs_rq * cfs_rq)989 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
990 {
991 return __pick_eevdf(cfs_rq, true);
992 }
993
__pick_last_entity(struct cfs_rq * cfs_rq)994 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
995 {
996 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
997
998 if (!last)
999 return NULL;
1000
1001 return __node_2_se(last);
1002 }
1003
1004 /**************************************************************
1005 * Scheduling class statistics methods:
1006 */
sched_update_scaling(void)1007 int sched_update_scaling(void)
1008 {
1009 unsigned int factor = get_update_sysctl_factor();
1010
1011 #define WRT_SYSCTL(name) \
1012 (normalized_sysctl_##name = sysctl_##name / (factor))
1013 WRT_SYSCTL(sched_base_slice);
1014 #undef WRT_SYSCTL
1015
1016 return 0;
1017 }
1018
1019 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1020
1021 /*
1022 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1023 * this is probably good enough.
1024 */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1025 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1026 {
1027 if ((s64)(se->vruntime - se->deadline) < 0)
1028 return false;
1029
1030 /*
1031 * For EEVDF the virtual time slope is determined by w_i (iow.
1032 * nice) while the request time r_i is determined by
1033 * sysctl_sched_base_slice.
1034 */
1035 if (!se->custom_slice)
1036 se->slice = sysctl_sched_base_slice;
1037
1038 /*
1039 * EEVDF: vd_i = ve_i + r_i / w_i
1040 */
1041 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1042
1043 /*
1044 * The task has consumed its request, reschedule.
1045 */
1046 return true;
1047 }
1048
1049 #include "pelt.h"
1050
1051 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1052 static unsigned long task_h_load(struct task_struct *p);
1053 static unsigned long capacity_of(int cpu);
1054
1055 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1056 void init_entity_runnable_average(struct sched_entity *se)
1057 {
1058 struct sched_avg *sa = &se->avg;
1059
1060 memset(sa, 0, sizeof(*sa));
1061
1062 /*
1063 * Tasks are initialized with full load to be seen as heavy tasks until
1064 * they get a chance to stabilize to their real load level.
1065 * Group entities are initialized with zero load to reflect the fact that
1066 * nothing has been attached to the task group yet.
1067 */
1068 if (entity_is_task(se))
1069 sa->load_avg = scale_load_down(se->load.weight);
1070
1071 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */
1072 }
1073
1074 /*
1075 * With new tasks being created, their initial util_avgs are extrapolated
1076 * based on the cfs_rq's current util_avg:
1077 *
1078 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1)
1079 * * se_weight(se)
1080 *
1081 * However, in many cases, the above util_avg does not give a desired
1082 * value. Moreover, the sum of the util_avgs may be divergent, such
1083 * as when the series is a harmonic series.
1084 *
1085 * To solve this problem, we also cap the util_avg of successive tasks to
1086 * only 1/2 of the left utilization budget:
1087 *
1088 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1089 *
1090 * where n denotes the nth task and cpu_scale the CPU capacity.
1091 *
1092 * For example, for a CPU with 1024 of capacity, a simplest series from
1093 * the beginning would be like:
1094 *
1095 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1096 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1097 *
1098 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1099 * if util_avg > util_avg_cap.
1100 */
post_init_entity_util_avg(struct task_struct * p)1101 void post_init_entity_util_avg(struct task_struct *p)
1102 {
1103 struct sched_entity *se = &p->se;
1104 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1105 struct sched_avg *sa = &se->avg;
1106 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1107 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1108
1109 if (p->sched_class != &fair_sched_class) {
1110 /*
1111 * For !fair tasks do:
1112 *
1113 update_cfs_rq_load_avg(now, cfs_rq);
1114 attach_entity_load_avg(cfs_rq, se);
1115 switched_from_fair(rq, p);
1116 *
1117 * such that the next switched_to_fair() has the
1118 * expected state.
1119 */
1120 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1121 return;
1122 }
1123
1124 if (cap > 0) {
1125 if (cfs_rq->avg.util_avg != 0) {
1126 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se);
1127 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1128
1129 if (sa->util_avg > cap)
1130 sa->util_avg = cap;
1131 } else {
1132 sa->util_avg = cap;
1133 }
1134 }
1135
1136 sa->runnable_avg = sa->util_avg;
1137 }
1138
update_se(struct rq * rq,struct sched_entity * se)1139 static s64 update_se(struct rq *rq, struct sched_entity *se)
1140 {
1141 u64 now = rq_clock_task(rq);
1142 s64 delta_exec;
1143
1144 delta_exec = now - se->exec_start;
1145 if (unlikely(delta_exec <= 0))
1146 return delta_exec;
1147
1148 se->exec_start = now;
1149 if (entity_is_task(se)) {
1150 struct task_struct *donor = task_of(se);
1151 struct task_struct *running = rq->curr;
1152 /*
1153 * If se is a task, we account the time against the running
1154 * task, as w/ proxy-exec they may not be the same.
1155 */
1156 running->se.exec_start = now;
1157 running->se.sum_exec_runtime += delta_exec;
1158
1159 trace_sched_stat_runtime(running, delta_exec);
1160 account_group_exec_runtime(running, delta_exec);
1161
1162 /* cgroup time is always accounted against the donor */
1163 cgroup_account_cputime(donor, delta_exec);
1164 } else {
1165 /* If not task, account the time against donor se */
1166 se->sum_exec_runtime += delta_exec;
1167 }
1168
1169 if (schedstat_enabled()) {
1170 struct sched_statistics *stats;
1171
1172 stats = __schedstats_from_se(se);
1173 __schedstat_set(stats->exec_max,
1174 max(delta_exec, stats->exec_max));
1175 }
1176
1177 return delta_exec;
1178 }
1179
1180 static void set_next_buddy(struct sched_entity *se);
1181
1182 /*
1183 * Used by other classes to account runtime.
1184 */
update_curr_common(struct rq * rq)1185 s64 update_curr_common(struct rq *rq)
1186 {
1187 return update_se(rq, &rq->donor->se);
1188 }
1189
1190 /*
1191 * Update the current task's runtime statistics.
1192 */
update_curr(struct cfs_rq * cfs_rq)1193 static void update_curr(struct cfs_rq *cfs_rq)
1194 {
1195 /*
1196 * Note: cfs_rq->curr corresponds to the task picked to
1197 * run (ie: rq->donor.se) which due to proxy-exec may
1198 * not necessarily be the actual task running
1199 * (rq->curr.se). This is easy to confuse!
1200 */
1201 struct sched_entity *curr = cfs_rq->curr;
1202 struct rq *rq = rq_of(cfs_rq);
1203 s64 delta_exec;
1204 bool resched;
1205
1206 if (unlikely(!curr))
1207 return;
1208
1209 delta_exec = update_se(rq, curr);
1210 if (unlikely(delta_exec <= 0))
1211 return;
1212
1213 curr->vruntime += calc_delta_fair(delta_exec, curr);
1214 resched = update_deadline(cfs_rq, curr);
1215
1216 if (entity_is_task(curr)) {
1217 /*
1218 * If the fair_server is active, we need to account for the
1219 * fair_server time whether or not the task is running on
1220 * behalf of fair_server or not:
1221 * - If the task is running on behalf of fair_server, we need
1222 * to limit its time based on the assigned runtime.
1223 * - Fair task that runs outside of fair_server should account
1224 * against fair_server such that it can account for this time
1225 * and possibly avoid running this period.
1226 */
1227 dl_server_update(&rq->fair_server, delta_exec);
1228 }
1229
1230 account_cfs_rq_runtime(cfs_rq, delta_exec);
1231
1232 if (cfs_rq->nr_queued == 1)
1233 return;
1234
1235 if (resched || !protect_slice(curr)) {
1236 resched_curr_lazy(rq);
1237 clear_buddies(cfs_rq, curr);
1238 }
1239 }
1240
update_curr_fair(struct rq * rq)1241 static void update_curr_fair(struct rq *rq)
1242 {
1243 update_curr(cfs_rq_of(&rq->donor->se));
1244 }
1245
1246 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1247 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1248 {
1249 struct sched_statistics *stats;
1250 struct task_struct *p = NULL;
1251
1252 if (!schedstat_enabled())
1253 return;
1254
1255 stats = __schedstats_from_se(se);
1256
1257 if (entity_is_task(se))
1258 p = task_of(se);
1259
1260 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1261 }
1262
1263 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1264 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1265 {
1266 struct sched_statistics *stats;
1267 struct task_struct *p = NULL;
1268
1269 if (!schedstat_enabled())
1270 return;
1271
1272 stats = __schedstats_from_se(se);
1273
1274 /*
1275 * When the sched_schedstat changes from 0 to 1, some sched se
1276 * maybe already in the runqueue, the se->statistics.wait_start
1277 * will be 0.So it will let the delta wrong. We need to avoid this
1278 * scenario.
1279 */
1280 if (unlikely(!schedstat_val(stats->wait_start)))
1281 return;
1282
1283 if (entity_is_task(se))
1284 p = task_of(se);
1285
1286 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1287 }
1288
1289 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1290 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1291 {
1292 struct sched_statistics *stats;
1293 struct task_struct *tsk = NULL;
1294
1295 if (!schedstat_enabled())
1296 return;
1297
1298 stats = __schedstats_from_se(se);
1299
1300 if (entity_is_task(se))
1301 tsk = task_of(se);
1302
1303 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1304 }
1305
1306 /*
1307 * Task is being enqueued - update stats:
1308 */
1309 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1310 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1311 {
1312 if (!schedstat_enabled())
1313 return;
1314
1315 /*
1316 * Are we enqueueing a waiting task? (for current tasks
1317 * a dequeue/enqueue event is a NOP)
1318 */
1319 if (se != cfs_rq->curr)
1320 update_stats_wait_start_fair(cfs_rq, se);
1321
1322 if (flags & ENQUEUE_WAKEUP)
1323 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1324 }
1325
1326 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1327 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1328 {
1329
1330 if (!schedstat_enabled())
1331 return;
1332
1333 /*
1334 * Mark the end of the wait period if dequeueing a
1335 * waiting task:
1336 */
1337 if (se != cfs_rq->curr)
1338 update_stats_wait_end_fair(cfs_rq, se);
1339
1340 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1341 struct task_struct *tsk = task_of(se);
1342 unsigned int state;
1343
1344 /* XXX racy against TTWU */
1345 state = READ_ONCE(tsk->__state);
1346 if (state & TASK_INTERRUPTIBLE)
1347 __schedstat_set(tsk->stats.sleep_start,
1348 rq_clock(rq_of(cfs_rq)));
1349 if (state & TASK_UNINTERRUPTIBLE)
1350 __schedstat_set(tsk->stats.block_start,
1351 rq_clock(rq_of(cfs_rq)));
1352 }
1353 }
1354
1355 /*
1356 * We are picking a new current task - update its stats:
1357 */
1358 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1359 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1360 {
1361 /*
1362 * We are starting a new run period:
1363 */
1364 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1365 }
1366
1367 /**************************************************
1368 * Scheduling class queueing methods:
1369 */
1370
is_core_idle(int cpu)1371 static inline bool is_core_idle(int cpu)
1372 {
1373 #ifdef CONFIG_SCHED_SMT
1374 int sibling;
1375
1376 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1377 if (cpu == sibling)
1378 continue;
1379
1380 if (!idle_cpu(sibling))
1381 return false;
1382 }
1383 #endif
1384
1385 return true;
1386 }
1387
1388 #ifdef CONFIG_NUMA
1389 #define NUMA_IMBALANCE_MIN 2
1390
1391 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1392 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1393 {
1394 /*
1395 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1396 * threshold. Above this threshold, individual tasks may be contending
1397 * for both memory bandwidth and any shared HT resources. This is an
1398 * approximation as the number of running tasks may not be related to
1399 * the number of busy CPUs due to sched_setaffinity.
1400 */
1401 if (dst_running > imb_numa_nr)
1402 return imbalance;
1403
1404 /*
1405 * Allow a small imbalance based on a simple pair of communicating
1406 * tasks that remain local when the destination is lightly loaded.
1407 */
1408 if (imbalance <= NUMA_IMBALANCE_MIN)
1409 return 0;
1410
1411 return imbalance;
1412 }
1413 #endif /* CONFIG_NUMA */
1414
1415 #ifdef CONFIG_NUMA_BALANCING
1416 /*
1417 * Approximate time to scan a full NUMA task in ms. The task scan period is
1418 * calculated based on the tasks virtual memory size and
1419 * numa_balancing_scan_size.
1420 */
1421 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1422 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1423
1424 /* Portion of address space to scan in MB */
1425 unsigned int sysctl_numa_balancing_scan_size = 256;
1426
1427 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1428 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1429
1430 /* The page with hint page fault latency < threshold in ms is considered hot */
1431 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1432
1433 struct numa_group {
1434 refcount_t refcount;
1435
1436 spinlock_t lock; /* nr_tasks, tasks */
1437 int nr_tasks;
1438 pid_t gid;
1439 int active_nodes;
1440
1441 struct rcu_head rcu;
1442 unsigned long total_faults;
1443 unsigned long max_faults_cpu;
1444 /*
1445 * faults[] array is split into two regions: faults_mem and faults_cpu.
1446 *
1447 * Faults_cpu is used to decide whether memory should move
1448 * towards the CPU. As a consequence, these stats are weighted
1449 * more by CPU use than by memory faults.
1450 */
1451 unsigned long faults[];
1452 };
1453
1454 /*
1455 * For functions that can be called in multiple contexts that permit reading
1456 * ->numa_group (see struct task_struct for locking rules).
1457 */
deref_task_numa_group(struct task_struct * p)1458 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1459 {
1460 return rcu_dereference_check(p->numa_group, p == current ||
1461 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1462 }
1463
deref_curr_numa_group(struct task_struct * p)1464 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1465 {
1466 return rcu_dereference_protected(p->numa_group, p == current);
1467 }
1468
1469 static inline unsigned long group_faults_priv(struct numa_group *ng);
1470 static inline unsigned long group_faults_shared(struct numa_group *ng);
1471
task_nr_scan_windows(struct task_struct * p)1472 static unsigned int task_nr_scan_windows(struct task_struct *p)
1473 {
1474 unsigned long rss = 0;
1475 unsigned long nr_scan_pages;
1476
1477 /*
1478 * Calculations based on RSS as non-present and empty pages are skipped
1479 * by the PTE scanner and NUMA hinting faults should be trapped based
1480 * on resident pages
1481 */
1482 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size);
1483 rss = get_mm_rss(p->mm);
1484 if (!rss)
1485 rss = nr_scan_pages;
1486
1487 rss = round_up(rss, nr_scan_pages);
1488 return rss / nr_scan_pages;
1489 }
1490
1491 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1492 #define MAX_SCAN_WINDOW 2560
1493
task_scan_min(struct task_struct * p)1494 static unsigned int task_scan_min(struct task_struct *p)
1495 {
1496 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1497 unsigned int scan, floor;
1498 unsigned int windows = 1;
1499
1500 if (scan_size < MAX_SCAN_WINDOW)
1501 windows = MAX_SCAN_WINDOW / scan_size;
1502 floor = 1000 / windows;
1503
1504 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1505 return max_t(unsigned int, floor, scan);
1506 }
1507
task_scan_start(struct task_struct * p)1508 static unsigned int task_scan_start(struct task_struct *p)
1509 {
1510 unsigned long smin = task_scan_min(p);
1511 unsigned long period = smin;
1512 struct numa_group *ng;
1513
1514 /* Scale the maximum scan period with the amount of shared memory. */
1515 rcu_read_lock();
1516 ng = rcu_dereference(p->numa_group);
1517 if (ng) {
1518 unsigned long shared = group_faults_shared(ng);
1519 unsigned long private = group_faults_priv(ng);
1520
1521 period *= refcount_read(&ng->refcount);
1522 period *= shared + 1;
1523 period /= private + shared + 1;
1524 }
1525 rcu_read_unlock();
1526
1527 return max(smin, period);
1528 }
1529
task_scan_max(struct task_struct * p)1530 static unsigned int task_scan_max(struct task_struct *p)
1531 {
1532 unsigned long smin = task_scan_min(p);
1533 unsigned long smax;
1534 struct numa_group *ng;
1535
1536 /* Watch for min being lower than max due to floor calculations */
1537 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1538
1539 /* Scale the maximum scan period with the amount of shared memory. */
1540 ng = deref_curr_numa_group(p);
1541 if (ng) {
1542 unsigned long shared = group_faults_shared(ng);
1543 unsigned long private = group_faults_priv(ng);
1544 unsigned long period = smax;
1545
1546 period *= refcount_read(&ng->refcount);
1547 period *= shared + 1;
1548 period /= private + shared + 1;
1549
1550 smax = max(smax, period);
1551 }
1552
1553 return max(smin, smax);
1554 }
1555
account_numa_enqueue(struct rq * rq,struct task_struct * p)1556 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1557 {
1558 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1559 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1560 }
1561
account_numa_dequeue(struct rq * rq,struct task_struct * p)1562 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1563 {
1564 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1565 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1566 }
1567
1568 /* Shared or private faults. */
1569 #define NR_NUMA_HINT_FAULT_TYPES 2
1570
1571 /* Memory and CPU locality */
1572 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1573
1574 /* Averaged statistics, and temporary buffers. */
1575 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1576
task_numa_group_id(struct task_struct * p)1577 pid_t task_numa_group_id(struct task_struct *p)
1578 {
1579 struct numa_group *ng;
1580 pid_t gid = 0;
1581
1582 rcu_read_lock();
1583 ng = rcu_dereference(p->numa_group);
1584 if (ng)
1585 gid = ng->gid;
1586 rcu_read_unlock();
1587
1588 return gid;
1589 }
1590
1591 /*
1592 * The averaged statistics, shared & private, memory & CPU,
1593 * occupy the first half of the array. The second half of the
1594 * array is for current counters, which are averaged into the
1595 * first set by task_numa_placement.
1596 */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1597 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1598 {
1599 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1600 }
1601
task_faults(struct task_struct * p,int nid)1602 static inline unsigned long task_faults(struct task_struct *p, int nid)
1603 {
1604 if (!p->numa_faults)
1605 return 0;
1606
1607 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1608 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1609 }
1610
group_faults(struct task_struct * p,int nid)1611 static inline unsigned long group_faults(struct task_struct *p, int nid)
1612 {
1613 struct numa_group *ng = deref_task_numa_group(p);
1614
1615 if (!ng)
1616 return 0;
1617
1618 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1619 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1620 }
1621
group_faults_cpu(struct numa_group * group,int nid)1622 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1623 {
1624 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1625 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1626 }
1627
group_faults_priv(struct numa_group * ng)1628 static inline unsigned long group_faults_priv(struct numa_group *ng)
1629 {
1630 unsigned long faults = 0;
1631 int node;
1632
1633 for_each_online_node(node) {
1634 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1635 }
1636
1637 return faults;
1638 }
1639
group_faults_shared(struct numa_group * ng)1640 static inline unsigned long group_faults_shared(struct numa_group *ng)
1641 {
1642 unsigned long faults = 0;
1643 int node;
1644
1645 for_each_online_node(node) {
1646 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1647 }
1648
1649 return faults;
1650 }
1651
1652 /*
1653 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1654 * considered part of a numa group's pseudo-interleaving set. Migrations
1655 * between these nodes are slowed down, to allow things to settle down.
1656 */
1657 #define ACTIVE_NODE_FRACTION 3
1658
numa_is_active_node(int nid,struct numa_group * ng)1659 static bool numa_is_active_node(int nid, struct numa_group *ng)
1660 {
1661 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1662 }
1663
1664 /* 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)1665 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1666 int lim_dist, bool task)
1667 {
1668 unsigned long score = 0;
1669 int node, max_dist;
1670
1671 /*
1672 * All nodes are directly connected, and the same distance
1673 * from each other. No need for fancy placement algorithms.
1674 */
1675 if (sched_numa_topology_type == NUMA_DIRECT)
1676 return 0;
1677
1678 /* sched_max_numa_distance may be changed in parallel. */
1679 max_dist = READ_ONCE(sched_max_numa_distance);
1680 /*
1681 * This code is called for each node, introducing N^2 complexity,
1682 * which should be OK given the number of nodes rarely exceeds 8.
1683 */
1684 for_each_online_node(node) {
1685 unsigned long faults;
1686 int dist = node_distance(nid, node);
1687
1688 /*
1689 * The furthest away nodes in the system are not interesting
1690 * for placement; nid was already counted.
1691 */
1692 if (dist >= max_dist || node == nid)
1693 continue;
1694
1695 /*
1696 * On systems with a backplane NUMA topology, compare groups
1697 * of nodes, and move tasks towards the group with the most
1698 * memory accesses. When comparing two nodes at distance
1699 * "hoplimit", only nodes closer by than "hoplimit" are part
1700 * of each group. Skip other nodes.
1701 */
1702 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1703 continue;
1704
1705 /* Add up the faults from nearby nodes. */
1706 if (task)
1707 faults = task_faults(p, node);
1708 else
1709 faults = group_faults(p, node);
1710
1711 /*
1712 * On systems with a glueless mesh NUMA topology, there are
1713 * no fixed "groups of nodes". Instead, nodes that are not
1714 * directly connected bounce traffic through intermediate
1715 * nodes; a numa_group can occupy any set of nodes.
1716 * The further away a node is, the less the faults count.
1717 * This seems to result in good task placement.
1718 */
1719 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1720 faults *= (max_dist - dist);
1721 faults /= (max_dist - LOCAL_DISTANCE);
1722 }
1723
1724 score += faults;
1725 }
1726
1727 return score;
1728 }
1729
1730 /*
1731 * These return the fraction of accesses done by a particular task, or
1732 * task group, on a particular numa node. The group weight is given a
1733 * larger multiplier, in order to group tasks together that are almost
1734 * evenly spread out between numa nodes.
1735 */
task_weight(struct task_struct * p,int nid,int dist)1736 static inline unsigned long task_weight(struct task_struct *p, int nid,
1737 int dist)
1738 {
1739 unsigned long faults, total_faults;
1740
1741 if (!p->numa_faults)
1742 return 0;
1743
1744 total_faults = p->total_numa_faults;
1745
1746 if (!total_faults)
1747 return 0;
1748
1749 faults = task_faults(p, nid);
1750 faults += score_nearby_nodes(p, nid, dist, true);
1751
1752 return 1000 * faults / total_faults;
1753 }
1754
group_weight(struct task_struct * p,int nid,int dist)1755 static inline unsigned long group_weight(struct task_struct *p, int nid,
1756 int dist)
1757 {
1758 struct numa_group *ng = deref_task_numa_group(p);
1759 unsigned long faults, total_faults;
1760
1761 if (!ng)
1762 return 0;
1763
1764 total_faults = ng->total_faults;
1765
1766 if (!total_faults)
1767 return 0;
1768
1769 faults = group_faults(p, nid);
1770 faults += score_nearby_nodes(p, nid, dist, false);
1771
1772 return 1000 * faults / total_faults;
1773 }
1774
1775 /*
1776 * If memory tiering mode is enabled, cpupid of slow memory page is
1777 * used to record scan time instead of CPU and PID. When tiering mode
1778 * is disabled at run time, the scan time (in cpupid) will be
1779 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1780 * access out of array bound.
1781 */
cpupid_valid(int cpupid)1782 static inline bool cpupid_valid(int cpupid)
1783 {
1784 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1785 }
1786
1787 /*
1788 * For memory tiering mode, if there are enough free pages (more than
1789 * enough watermark defined here) in fast memory node, to take full
1790 * advantage of fast memory capacity, all recently accessed slow
1791 * memory pages will be migrated to fast memory node without
1792 * considering hot threshold.
1793 */
pgdat_free_space_enough(struct pglist_data * pgdat)1794 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1795 {
1796 int z;
1797 unsigned long enough_wmark;
1798
1799 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1800 pgdat->node_present_pages >> 4);
1801 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1802 struct zone *zone = pgdat->node_zones + z;
1803
1804 if (!populated_zone(zone))
1805 continue;
1806
1807 if (zone_watermark_ok(zone, 0,
1808 promo_wmark_pages(zone) + enough_wmark,
1809 ZONE_MOVABLE, 0))
1810 return true;
1811 }
1812 return false;
1813 }
1814
1815 /*
1816 * For memory tiering mode, when page tables are scanned, the scan
1817 * time will be recorded in struct page in addition to make page
1818 * PROT_NONE for slow memory page. So when the page is accessed, in
1819 * hint page fault handler, the hint page fault latency is calculated
1820 * via,
1821 *
1822 * hint page fault latency = hint page fault time - scan time
1823 *
1824 * The smaller the hint page fault latency, the higher the possibility
1825 * for the page to be hot.
1826 */
numa_hint_fault_latency(struct folio * folio)1827 static int numa_hint_fault_latency(struct folio *folio)
1828 {
1829 int last_time, time;
1830
1831 time = jiffies_to_msecs(jiffies);
1832 last_time = folio_xchg_access_time(folio, time);
1833
1834 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1835 }
1836
1837 /*
1838 * For memory tiering mode, too high promotion/demotion throughput may
1839 * hurt application latency. So we provide a mechanism to rate limit
1840 * the number of pages that are tried to be promoted.
1841 */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)1842 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1843 unsigned long rate_limit, int nr)
1844 {
1845 unsigned long nr_cand;
1846 unsigned int now, start;
1847
1848 now = jiffies_to_msecs(jiffies);
1849 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1850 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1851 start = pgdat->nbp_rl_start;
1852 if (now - start > MSEC_PER_SEC &&
1853 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1854 pgdat->nbp_rl_nr_cand = nr_cand;
1855 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1856 return true;
1857 return false;
1858 }
1859
1860 #define NUMA_MIGRATION_ADJUST_STEPS 16
1861
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)1862 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1863 unsigned long rate_limit,
1864 unsigned int ref_th)
1865 {
1866 unsigned int now, start, th_period, unit_th, th;
1867 unsigned long nr_cand, ref_cand, diff_cand;
1868
1869 now = jiffies_to_msecs(jiffies);
1870 th_period = sysctl_numa_balancing_scan_period_max;
1871 start = pgdat->nbp_th_start;
1872 if (now - start > th_period &&
1873 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1874 ref_cand = rate_limit *
1875 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1876 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1877 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1878 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1879 th = pgdat->nbp_threshold ? : ref_th;
1880 if (diff_cand > ref_cand * 11 / 10)
1881 th = max(th - unit_th, unit_th);
1882 else if (diff_cand < ref_cand * 9 / 10)
1883 th = min(th + unit_th, ref_th * 2);
1884 pgdat->nbp_th_nr_cand = nr_cand;
1885 pgdat->nbp_threshold = th;
1886 }
1887 }
1888
should_numa_migrate_memory(struct task_struct * p,struct folio * folio,int src_nid,int dst_cpu)1889 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio,
1890 int src_nid, int dst_cpu)
1891 {
1892 struct numa_group *ng = deref_curr_numa_group(p);
1893 int dst_nid = cpu_to_node(dst_cpu);
1894 int last_cpupid, this_cpupid;
1895
1896 /*
1897 * Cannot migrate to memoryless nodes.
1898 */
1899 if (!node_state(dst_nid, N_MEMORY))
1900 return false;
1901
1902 /*
1903 * The pages in slow memory node should be migrated according
1904 * to hot/cold instead of private/shared.
1905 */
1906 if (folio_use_access_time(folio)) {
1907 struct pglist_data *pgdat;
1908 unsigned long rate_limit;
1909 unsigned int latency, th, def_th;
1910 long nr = folio_nr_pages(folio);
1911
1912 pgdat = NODE_DATA(dst_nid);
1913 if (pgdat_free_space_enough(pgdat)) {
1914 /* workload changed, reset hot threshold */
1915 pgdat->nbp_threshold = 0;
1916 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr);
1917 return true;
1918 }
1919
1920 def_th = sysctl_numa_balancing_hot_threshold;
1921 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit);
1922 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1923
1924 th = pgdat->nbp_threshold ? : def_th;
1925 latency = numa_hint_fault_latency(folio);
1926 if (latency >= th)
1927 return false;
1928
1929 return !numa_promotion_rate_limit(pgdat, rate_limit, nr);
1930 }
1931
1932 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1933 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid);
1934
1935 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1936 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1937 return false;
1938
1939 /*
1940 * Allow first faults or private faults to migrate immediately early in
1941 * the lifetime of a task. The magic number 4 is based on waiting for
1942 * two full passes of the "multi-stage node selection" test that is
1943 * executed below.
1944 */
1945 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1946 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1947 return true;
1948
1949 /*
1950 * Multi-stage node selection is used in conjunction with a periodic
1951 * migration fault to build a temporal task<->page relation. By using
1952 * a two-stage filter we remove short/unlikely relations.
1953 *
1954 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1955 * a task's usage of a particular page (n_p) per total usage of this
1956 * page (n_t) (in a given time-span) to a probability.
1957 *
1958 * Our periodic faults will sample this probability and getting the
1959 * same result twice in a row, given these samples are fully
1960 * independent, is then given by P(n)^2, provided our sample period
1961 * is sufficiently short compared to the usage pattern.
1962 *
1963 * This quadric squishes small probabilities, making it less likely we
1964 * act on an unlikely task<->page relation.
1965 */
1966 if (!cpupid_pid_unset(last_cpupid) &&
1967 cpupid_to_nid(last_cpupid) != dst_nid)
1968 return false;
1969
1970 /* Always allow migrate on private faults */
1971 if (cpupid_match_pid(p, last_cpupid))
1972 return true;
1973
1974 /* A shared fault, but p->numa_group has not been set up yet. */
1975 if (!ng)
1976 return true;
1977
1978 /*
1979 * Destination node is much more heavily used than the source
1980 * node? Allow migration.
1981 */
1982 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1983 ACTIVE_NODE_FRACTION)
1984 return true;
1985
1986 /*
1987 * Distribute memory according to CPU & memory use on each node,
1988 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1989 *
1990 * faults_cpu(dst) 3 faults_cpu(src)
1991 * --------------- * - > ---------------
1992 * faults_mem(dst) 4 faults_mem(src)
1993 */
1994 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1995 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1996 }
1997
1998 /*
1999 * 'numa_type' describes the node at the moment of load balancing.
2000 */
2001 enum numa_type {
2002 /* The node has spare capacity that can be used to run more tasks. */
2003 node_has_spare = 0,
2004 /*
2005 * The node is fully used and the tasks don't compete for more CPU
2006 * cycles. Nevertheless, some tasks might wait before running.
2007 */
2008 node_fully_busy,
2009 /*
2010 * The node is overloaded and can't provide expected CPU cycles to all
2011 * tasks.
2012 */
2013 node_overloaded
2014 };
2015
2016 /* Cached statistics for all CPUs within a node */
2017 struct numa_stats {
2018 unsigned long load;
2019 unsigned long runnable;
2020 unsigned long util;
2021 /* Total compute capacity of CPUs on a node */
2022 unsigned long compute_capacity;
2023 unsigned int nr_running;
2024 unsigned int weight;
2025 enum numa_type node_type;
2026 int idle_cpu;
2027 };
2028
2029 struct task_numa_env {
2030 struct task_struct *p;
2031
2032 int src_cpu, src_nid;
2033 int dst_cpu, dst_nid;
2034 int imb_numa_nr;
2035
2036 struct numa_stats src_stats, dst_stats;
2037
2038 int imbalance_pct;
2039 int dist;
2040
2041 struct task_struct *best_task;
2042 long best_imp;
2043 int best_cpu;
2044 };
2045
2046 static unsigned long cpu_load(struct rq *rq);
2047 static unsigned long cpu_runnable(struct rq *rq);
2048
2049 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2050 numa_type numa_classify(unsigned int imbalance_pct,
2051 struct numa_stats *ns)
2052 {
2053 if ((ns->nr_running > ns->weight) &&
2054 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2055 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2056 return node_overloaded;
2057
2058 if ((ns->nr_running < ns->weight) ||
2059 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2060 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2061 return node_has_spare;
2062
2063 return node_fully_busy;
2064 }
2065
2066 #ifdef CONFIG_SCHED_SMT
2067 /* Forward declarations of select_idle_sibling helpers */
2068 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2069 static inline int numa_idle_core(int idle_core, int cpu)
2070 {
2071 if (!static_branch_likely(&sched_smt_present) ||
2072 idle_core >= 0 || !test_idle_cores(cpu))
2073 return idle_core;
2074
2075 /*
2076 * Prefer cores instead of packing HT siblings
2077 * and triggering future load balancing.
2078 */
2079 if (is_core_idle(cpu))
2080 idle_core = cpu;
2081
2082 return idle_core;
2083 }
2084 #else /* !CONFIG_SCHED_SMT: */
numa_idle_core(int idle_core,int cpu)2085 static inline int numa_idle_core(int idle_core, int cpu)
2086 {
2087 return idle_core;
2088 }
2089 #endif /* !CONFIG_SCHED_SMT */
2090
2091 /*
2092 * Gather all necessary information to make NUMA balancing placement
2093 * decisions that are compatible with standard load balancer. This
2094 * borrows code and logic from update_sg_lb_stats but sharing a
2095 * common implementation is impractical.
2096 */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2097 static void update_numa_stats(struct task_numa_env *env,
2098 struct numa_stats *ns, int nid,
2099 bool find_idle)
2100 {
2101 int cpu, idle_core = -1;
2102
2103 memset(ns, 0, sizeof(*ns));
2104 ns->idle_cpu = -1;
2105
2106 rcu_read_lock();
2107 for_each_cpu(cpu, cpumask_of_node(nid)) {
2108 struct rq *rq = cpu_rq(cpu);
2109
2110 ns->load += cpu_load(rq);
2111 ns->runnable += cpu_runnable(rq);
2112 ns->util += cpu_util_cfs(cpu);
2113 ns->nr_running += rq->cfs.h_nr_runnable;
2114 ns->compute_capacity += capacity_of(cpu);
2115
2116 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2117 if (READ_ONCE(rq->numa_migrate_on) ||
2118 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2119 continue;
2120
2121 if (ns->idle_cpu == -1)
2122 ns->idle_cpu = cpu;
2123
2124 idle_core = numa_idle_core(idle_core, cpu);
2125 }
2126 }
2127 rcu_read_unlock();
2128
2129 ns->weight = cpumask_weight(cpumask_of_node(nid));
2130
2131 ns->node_type = numa_classify(env->imbalance_pct, ns);
2132
2133 if (idle_core >= 0)
2134 ns->idle_cpu = idle_core;
2135 }
2136
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2137 static void task_numa_assign(struct task_numa_env *env,
2138 struct task_struct *p, long imp)
2139 {
2140 struct rq *rq = cpu_rq(env->dst_cpu);
2141
2142 /* Check if run-queue part of active NUMA balance. */
2143 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2144 int cpu;
2145 int start = env->dst_cpu;
2146
2147 /* Find alternative idle CPU. */
2148 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2149 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2150 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2151 continue;
2152 }
2153
2154 env->dst_cpu = cpu;
2155 rq = cpu_rq(env->dst_cpu);
2156 if (!xchg(&rq->numa_migrate_on, 1))
2157 goto assign;
2158 }
2159
2160 /* Failed to find an alternative idle CPU */
2161 return;
2162 }
2163
2164 assign:
2165 /*
2166 * Clear previous best_cpu/rq numa-migrate flag, since task now
2167 * found a better CPU to move/swap.
2168 */
2169 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2170 rq = cpu_rq(env->best_cpu);
2171 WRITE_ONCE(rq->numa_migrate_on, 0);
2172 }
2173
2174 if (env->best_task)
2175 put_task_struct(env->best_task);
2176 if (p)
2177 get_task_struct(p);
2178
2179 env->best_task = p;
2180 env->best_imp = imp;
2181 env->best_cpu = env->dst_cpu;
2182 }
2183
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2184 static bool load_too_imbalanced(long src_load, long dst_load,
2185 struct task_numa_env *env)
2186 {
2187 long imb, old_imb;
2188 long orig_src_load, orig_dst_load;
2189 long src_capacity, dst_capacity;
2190
2191 /*
2192 * The load is corrected for the CPU capacity available on each node.
2193 *
2194 * src_load dst_load
2195 * ------------ vs ---------
2196 * src_capacity dst_capacity
2197 */
2198 src_capacity = env->src_stats.compute_capacity;
2199 dst_capacity = env->dst_stats.compute_capacity;
2200
2201 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2202
2203 orig_src_load = env->src_stats.load;
2204 orig_dst_load = env->dst_stats.load;
2205
2206 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2207
2208 /* Would this change make things worse? */
2209 return (imb > old_imb);
2210 }
2211
2212 /*
2213 * Maximum NUMA importance can be 1998 (2*999);
2214 * SMALLIMP @ 30 would be close to 1998/64.
2215 * Used to deter task migration.
2216 */
2217 #define SMALLIMP 30
2218
2219 /*
2220 * This checks if the overall compute and NUMA accesses of the system would
2221 * be improved if the source tasks was migrated to the target dst_cpu taking
2222 * into account that it might be best if task running on the dst_cpu should
2223 * be exchanged with the source task
2224 */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2225 static bool task_numa_compare(struct task_numa_env *env,
2226 long taskimp, long groupimp, bool maymove)
2227 {
2228 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2229 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2230 long imp = p_ng ? groupimp : taskimp;
2231 struct task_struct *cur;
2232 long src_load, dst_load;
2233 int dist = env->dist;
2234 long moveimp = imp;
2235 long load;
2236 bool stopsearch = false;
2237
2238 if (READ_ONCE(dst_rq->numa_migrate_on))
2239 return false;
2240
2241 rcu_read_lock();
2242 cur = rcu_dereference(dst_rq->curr);
2243 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) ||
2244 !cur->mm))
2245 cur = NULL;
2246
2247 /*
2248 * Because we have preemption enabled we can get migrated around and
2249 * end try selecting ourselves (current == env->p) as a swap candidate.
2250 */
2251 if (cur == env->p) {
2252 stopsearch = true;
2253 goto unlock;
2254 }
2255
2256 if (!cur) {
2257 if (maymove && moveimp >= env->best_imp)
2258 goto assign;
2259 else
2260 goto unlock;
2261 }
2262
2263 /* Skip this swap candidate if cannot move to the source cpu. */
2264 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2265 goto unlock;
2266
2267 /*
2268 * Skip this swap candidate if it is not moving to its preferred
2269 * node and the best task is.
2270 */
2271 if (env->best_task &&
2272 env->best_task->numa_preferred_nid == env->src_nid &&
2273 cur->numa_preferred_nid != env->src_nid) {
2274 goto unlock;
2275 }
2276
2277 /*
2278 * "imp" is the fault differential for the source task between the
2279 * source and destination node. Calculate the total differential for
2280 * the source task and potential destination task. The more negative
2281 * the value is, the more remote accesses that would be expected to
2282 * be incurred if the tasks were swapped.
2283 *
2284 * If dst and source tasks are in the same NUMA group, or not
2285 * in any group then look only at task weights.
2286 */
2287 cur_ng = rcu_dereference(cur->numa_group);
2288 if (cur_ng == p_ng) {
2289 /*
2290 * Do not swap within a group or between tasks that have
2291 * no group if there is spare capacity. Swapping does
2292 * not address the load imbalance and helps one task at
2293 * the cost of punishing another.
2294 */
2295 if (env->dst_stats.node_type == node_has_spare)
2296 goto unlock;
2297
2298 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2299 task_weight(cur, env->dst_nid, dist);
2300 /*
2301 * Add some hysteresis to prevent swapping the
2302 * tasks within a group over tiny differences.
2303 */
2304 if (cur_ng)
2305 imp -= imp / 16;
2306 } else {
2307 /*
2308 * Compare the group weights. If a task is all by itself
2309 * (not part of a group), use the task weight instead.
2310 */
2311 if (cur_ng && p_ng)
2312 imp += group_weight(cur, env->src_nid, dist) -
2313 group_weight(cur, env->dst_nid, dist);
2314 else
2315 imp += task_weight(cur, env->src_nid, dist) -
2316 task_weight(cur, env->dst_nid, dist);
2317 }
2318
2319 /* Discourage picking a task already on its preferred node */
2320 if (cur->numa_preferred_nid == env->dst_nid)
2321 imp -= imp / 16;
2322
2323 /*
2324 * Encourage picking a task that moves to its preferred node.
2325 * This potentially makes imp larger than it's maximum of
2326 * 1998 (see SMALLIMP and task_weight for why) but in this
2327 * case, it does not matter.
2328 */
2329 if (cur->numa_preferred_nid == env->src_nid)
2330 imp += imp / 8;
2331
2332 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2333 imp = moveimp;
2334 cur = NULL;
2335 goto assign;
2336 }
2337
2338 /*
2339 * Prefer swapping with a task moving to its preferred node over a
2340 * task that is not.
2341 */
2342 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2343 env->best_task->numa_preferred_nid != env->src_nid) {
2344 goto assign;
2345 }
2346
2347 /*
2348 * If the NUMA importance is less than SMALLIMP,
2349 * task migration might only result in ping pong
2350 * of tasks and also hurt performance due to cache
2351 * misses.
2352 */
2353 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2354 goto unlock;
2355
2356 /*
2357 * In the overloaded case, try and keep the load balanced.
2358 */
2359 load = task_h_load(env->p) - task_h_load(cur);
2360 if (!load)
2361 goto assign;
2362
2363 dst_load = env->dst_stats.load + load;
2364 src_load = env->src_stats.load - load;
2365
2366 if (load_too_imbalanced(src_load, dst_load, env))
2367 goto unlock;
2368
2369 assign:
2370 /* Evaluate an idle CPU for a task numa move. */
2371 if (!cur) {
2372 int cpu = env->dst_stats.idle_cpu;
2373
2374 /* Nothing cached so current CPU went idle since the search. */
2375 if (cpu < 0)
2376 cpu = env->dst_cpu;
2377
2378 /*
2379 * If the CPU is no longer truly idle and the previous best CPU
2380 * is, keep using it.
2381 */
2382 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2383 idle_cpu(env->best_cpu)) {
2384 cpu = env->best_cpu;
2385 }
2386
2387 env->dst_cpu = cpu;
2388 }
2389
2390 task_numa_assign(env, cur, imp);
2391
2392 /*
2393 * If a move to idle is allowed because there is capacity or load
2394 * balance improves then stop the search. While a better swap
2395 * candidate may exist, a search is not free.
2396 */
2397 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2398 stopsearch = true;
2399
2400 /*
2401 * If a swap candidate must be identified and the current best task
2402 * moves its preferred node then stop the search.
2403 */
2404 if (!maymove && env->best_task &&
2405 env->best_task->numa_preferred_nid == env->src_nid) {
2406 stopsearch = true;
2407 }
2408 unlock:
2409 rcu_read_unlock();
2410
2411 return stopsearch;
2412 }
2413
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2414 static void task_numa_find_cpu(struct task_numa_env *env,
2415 long taskimp, long groupimp)
2416 {
2417 bool maymove = false;
2418 int cpu;
2419
2420 /*
2421 * If dst node has spare capacity, then check if there is an
2422 * imbalance that would be overruled by the load balancer.
2423 */
2424 if (env->dst_stats.node_type == node_has_spare) {
2425 unsigned int imbalance;
2426 int src_running, dst_running;
2427
2428 /*
2429 * Would movement cause an imbalance? Note that if src has
2430 * more running tasks that the imbalance is ignored as the
2431 * move improves the imbalance from the perspective of the
2432 * CPU load balancer.
2433 * */
2434 src_running = env->src_stats.nr_running - 1;
2435 dst_running = env->dst_stats.nr_running + 1;
2436 imbalance = max(0, dst_running - src_running);
2437 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2438 env->imb_numa_nr);
2439
2440 /* Use idle CPU if there is no imbalance */
2441 if (!imbalance) {
2442 maymove = true;
2443 if (env->dst_stats.idle_cpu >= 0) {
2444 env->dst_cpu = env->dst_stats.idle_cpu;
2445 task_numa_assign(env, NULL, 0);
2446 return;
2447 }
2448 }
2449 } else {
2450 long src_load, dst_load, load;
2451 /*
2452 * If the improvement from just moving env->p direction is better
2453 * than swapping tasks around, check if a move is possible.
2454 */
2455 load = task_h_load(env->p);
2456 dst_load = env->dst_stats.load + load;
2457 src_load = env->src_stats.load - load;
2458 maymove = !load_too_imbalanced(src_load, dst_load, env);
2459 }
2460
2461 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2462 /* Skip this CPU if the source task cannot migrate */
2463 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2464 continue;
2465
2466 env->dst_cpu = cpu;
2467 if (task_numa_compare(env, taskimp, groupimp, maymove))
2468 break;
2469 }
2470 }
2471
task_numa_migrate(struct task_struct * p)2472 static int task_numa_migrate(struct task_struct *p)
2473 {
2474 struct task_numa_env env = {
2475 .p = p,
2476
2477 .src_cpu = task_cpu(p),
2478 .src_nid = task_node(p),
2479
2480 .imbalance_pct = 112,
2481
2482 .best_task = NULL,
2483 .best_imp = 0,
2484 .best_cpu = -1,
2485 };
2486 unsigned long taskweight, groupweight;
2487 struct sched_domain *sd;
2488 long taskimp, groupimp;
2489 struct numa_group *ng;
2490 struct rq *best_rq;
2491 int nid, ret, dist;
2492
2493 /*
2494 * Pick the lowest SD_NUMA domain, as that would have the smallest
2495 * imbalance and would be the first to start moving tasks about.
2496 *
2497 * And we want to avoid any moving of tasks about, as that would create
2498 * random movement of tasks -- counter the numa conditions we're trying
2499 * to satisfy here.
2500 */
2501 rcu_read_lock();
2502 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2503 if (sd) {
2504 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2505 env.imb_numa_nr = sd->imb_numa_nr;
2506 }
2507 rcu_read_unlock();
2508
2509 /*
2510 * Cpusets can break the scheduler domain tree into smaller
2511 * balance domains, some of which do not cross NUMA boundaries.
2512 * Tasks that are "trapped" in such domains cannot be migrated
2513 * elsewhere, so there is no point in (re)trying.
2514 */
2515 if (unlikely(!sd)) {
2516 sched_setnuma(p, task_node(p));
2517 return -EINVAL;
2518 }
2519
2520 env.dst_nid = p->numa_preferred_nid;
2521 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2522 taskweight = task_weight(p, env.src_nid, dist);
2523 groupweight = group_weight(p, env.src_nid, dist);
2524 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2525 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2526 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2527 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2528
2529 /* Try to find a spot on the preferred nid. */
2530 task_numa_find_cpu(&env, taskimp, groupimp);
2531
2532 /*
2533 * Look at other nodes in these cases:
2534 * - there is no space available on the preferred_nid
2535 * - the task is part of a numa_group that is interleaved across
2536 * multiple NUMA nodes; in order to better consolidate the group,
2537 * we need to check other locations.
2538 */
2539 ng = deref_curr_numa_group(p);
2540 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2541 for_each_node_state(nid, N_CPU) {
2542 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2543 continue;
2544
2545 dist = node_distance(env.src_nid, env.dst_nid);
2546 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2547 dist != env.dist) {
2548 taskweight = task_weight(p, env.src_nid, dist);
2549 groupweight = group_weight(p, env.src_nid, dist);
2550 }
2551
2552 /* Only consider nodes where both task and groups benefit */
2553 taskimp = task_weight(p, nid, dist) - taskweight;
2554 groupimp = group_weight(p, nid, dist) - groupweight;
2555 if (taskimp < 0 && groupimp < 0)
2556 continue;
2557
2558 env.dist = dist;
2559 env.dst_nid = nid;
2560 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2561 task_numa_find_cpu(&env, taskimp, groupimp);
2562 }
2563 }
2564
2565 /*
2566 * If the task is part of a workload that spans multiple NUMA nodes,
2567 * and is migrating into one of the workload's active nodes, remember
2568 * this node as the task's preferred numa node, so the workload can
2569 * settle down.
2570 * A task that migrated to a second choice node will be better off
2571 * trying for a better one later. Do not set the preferred node here.
2572 */
2573 if (ng) {
2574 if (env.best_cpu == -1)
2575 nid = env.src_nid;
2576 else
2577 nid = cpu_to_node(env.best_cpu);
2578
2579 if (nid != p->numa_preferred_nid)
2580 sched_setnuma(p, nid);
2581 }
2582
2583 /* No better CPU than the current one was found. */
2584 if (env.best_cpu == -1) {
2585 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2586 return -EAGAIN;
2587 }
2588
2589 best_rq = cpu_rq(env.best_cpu);
2590 if (env.best_task == NULL) {
2591 ret = migrate_task_to(p, env.best_cpu);
2592 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2593 if (ret != 0)
2594 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2595 return ret;
2596 }
2597
2598 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2599 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2600
2601 if (ret != 0)
2602 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2603 put_task_struct(env.best_task);
2604 return ret;
2605 }
2606
2607 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2608 static void numa_migrate_preferred(struct task_struct *p)
2609 {
2610 unsigned long interval = HZ;
2611
2612 /* This task has no NUMA fault statistics yet */
2613 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2614 return;
2615
2616 /* Periodically retry migrating the task to the preferred node */
2617 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2618 p->numa_migrate_retry = jiffies + interval;
2619
2620 /* Success if task is already running on preferred CPU */
2621 if (task_node(p) == p->numa_preferred_nid)
2622 return;
2623
2624 /* Otherwise, try migrate to a CPU on the preferred node */
2625 task_numa_migrate(p);
2626 }
2627
2628 /*
2629 * Find out how many nodes the workload is actively running on. Do this by
2630 * tracking the nodes from which NUMA hinting faults are triggered. This can
2631 * be different from the set of nodes where the workload's memory is currently
2632 * located.
2633 */
numa_group_count_active_nodes(struct numa_group * numa_group)2634 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2635 {
2636 unsigned long faults, max_faults = 0;
2637 int nid, active_nodes = 0;
2638
2639 for_each_node_state(nid, N_CPU) {
2640 faults = group_faults_cpu(numa_group, nid);
2641 if (faults > max_faults)
2642 max_faults = faults;
2643 }
2644
2645 for_each_node_state(nid, N_CPU) {
2646 faults = group_faults_cpu(numa_group, nid);
2647 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2648 active_nodes++;
2649 }
2650
2651 numa_group->max_faults_cpu = max_faults;
2652 numa_group->active_nodes = active_nodes;
2653 }
2654
2655 /*
2656 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2657 * increments. The more local the fault statistics are, the higher the scan
2658 * period will be for the next scan window. If local/(local+remote) ratio is
2659 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2660 * the scan period will decrease. Aim for 70% local accesses.
2661 */
2662 #define NUMA_PERIOD_SLOTS 10
2663 #define NUMA_PERIOD_THRESHOLD 7
2664
2665 /*
2666 * Increase the scan period (slow down scanning) if the majority of
2667 * our memory is already on our local node, or if the majority of
2668 * the page accesses are shared with other processes.
2669 * Otherwise, decrease the scan period.
2670 */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2671 static void update_task_scan_period(struct task_struct *p,
2672 unsigned long shared, unsigned long private)
2673 {
2674 unsigned int period_slot;
2675 int lr_ratio, ps_ratio;
2676 int diff;
2677
2678 unsigned long remote = p->numa_faults_locality[0];
2679 unsigned long local = p->numa_faults_locality[1];
2680
2681 /*
2682 * If there were no record hinting faults then either the task is
2683 * completely idle or all activity is in areas that are not of interest
2684 * to automatic numa balancing. Related to that, if there were failed
2685 * migration then it implies we are migrating too quickly or the local
2686 * node is overloaded. In either case, scan slower
2687 */
2688 if (local + shared == 0 || p->numa_faults_locality[2]) {
2689 p->numa_scan_period = min(p->numa_scan_period_max,
2690 p->numa_scan_period << 1);
2691
2692 p->mm->numa_next_scan = jiffies +
2693 msecs_to_jiffies(p->numa_scan_period);
2694
2695 return;
2696 }
2697
2698 /*
2699 * Prepare to scale scan period relative to the current period.
2700 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2701 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2702 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2703 */
2704 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2705 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2706 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2707
2708 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2709 /*
2710 * Most memory accesses are local. There is no need to
2711 * do fast NUMA scanning, since memory is already local.
2712 */
2713 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2714 if (!slot)
2715 slot = 1;
2716 diff = slot * period_slot;
2717 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2718 /*
2719 * Most memory accesses are shared with other tasks.
2720 * There is no point in continuing fast NUMA scanning,
2721 * since other tasks may just move the memory elsewhere.
2722 */
2723 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2724 if (!slot)
2725 slot = 1;
2726 diff = slot * period_slot;
2727 } else {
2728 /*
2729 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2730 * yet they are not on the local NUMA node. Speed up
2731 * NUMA scanning to get the memory moved over.
2732 */
2733 int ratio = max(lr_ratio, ps_ratio);
2734 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2735 }
2736
2737 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2738 task_scan_min(p), task_scan_max(p));
2739 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2740 }
2741
2742 /*
2743 * Get the fraction of time the task has been running since the last
2744 * NUMA placement cycle. The scheduler keeps similar statistics, but
2745 * decays those on a 32ms period, which is orders of magnitude off
2746 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2747 * stats only if the task is so new there are no NUMA statistics yet.
2748 */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2749 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2750 {
2751 u64 runtime, delta, now;
2752 /* Use the start of this time slice to avoid calculations. */
2753 now = p->se.exec_start;
2754 runtime = p->se.sum_exec_runtime;
2755
2756 if (p->last_task_numa_placement) {
2757 delta = runtime - p->last_sum_exec_runtime;
2758 *period = now - p->last_task_numa_placement;
2759
2760 /* Avoid time going backwards, prevent potential divide error: */
2761 if (unlikely((s64)*period < 0))
2762 *period = 0;
2763 } else {
2764 delta = p->se.avg.load_sum;
2765 *period = LOAD_AVG_MAX;
2766 }
2767
2768 p->last_sum_exec_runtime = runtime;
2769 p->last_task_numa_placement = now;
2770
2771 return delta;
2772 }
2773
2774 /*
2775 * Determine the preferred nid for a task in a numa_group. This needs to
2776 * be done in a way that produces consistent results with group_weight,
2777 * otherwise workloads might not converge.
2778 */
preferred_group_nid(struct task_struct * p,int nid)2779 static int preferred_group_nid(struct task_struct *p, int nid)
2780 {
2781 nodemask_t nodes;
2782 int dist;
2783
2784 /* Direct connections between all NUMA nodes. */
2785 if (sched_numa_topology_type == NUMA_DIRECT)
2786 return nid;
2787
2788 /*
2789 * On a system with glueless mesh NUMA topology, group_weight
2790 * scores nodes according to the number of NUMA hinting faults on
2791 * both the node itself, and on nearby nodes.
2792 */
2793 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2794 unsigned long score, max_score = 0;
2795 int node, max_node = nid;
2796
2797 dist = sched_max_numa_distance;
2798
2799 for_each_node_state(node, N_CPU) {
2800 score = group_weight(p, node, dist);
2801 if (score > max_score) {
2802 max_score = score;
2803 max_node = node;
2804 }
2805 }
2806 return max_node;
2807 }
2808
2809 /*
2810 * Finding the preferred nid in a system with NUMA backplane
2811 * interconnect topology is more involved. The goal is to locate
2812 * tasks from numa_groups near each other in the system, and
2813 * untangle workloads from different sides of the system. This requires
2814 * searching down the hierarchy of node groups, recursively searching
2815 * inside the highest scoring group of nodes. The nodemask tricks
2816 * keep the complexity of the search down.
2817 */
2818 nodes = node_states[N_CPU];
2819 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2820 unsigned long max_faults = 0;
2821 nodemask_t max_group = NODE_MASK_NONE;
2822 int a, b;
2823
2824 /* Are there nodes at this distance from each other? */
2825 if (!find_numa_distance(dist))
2826 continue;
2827
2828 for_each_node_mask(a, nodes) {
2829 unsigned long faults = 0;
2830 nodemask_t this_group;
2831 nodes_clear(this_group);
2832
2833 /* Sum group's NUMA faults; includes a==b case. */
2834 for_each_node_mask(b, nodes) {
2835 if (node_distance(a, b) < dist) {
2836 faults += group_faults(p, b);
2837 node_set(b, this_group);
2838 node_clear(b, nodes);
2839 }
2840 }
2841
2842 /* Remember the top group. */
2843 if (faults > max_faults) {
2844 max_faults = faults;
2845 max_group = this_group;
2846 /*
2847 * subtle: at the smallest distance there is
2848 * just one node left in each "group", the
2849 * winner is the preferred nid.
2850 */
2851 nid = a;
2852 }
2853 }
2854 /* Next round, evaluate the nodes within max_group. */
2855 if (!max_faults)
2856 break;
2857 nodes = max_group;
2858 }
2859 return nid;
2860 }
2861
task_numa_placement(struct task_struct * p)2862 static void task_numa_placement(struct task_struct *p)
2863 {
2864 int seq, nid, max_nid = NUMA_NO_NODE;
2865 unsigned long max_faults = 0;
2866 unsigned long fault_types[2] = { 0, 0 };
2867 unsigned long total_faults;
2868 u64 runtime, period;
2869 spinlock_t *group_lock = NULL;
2870 struct numa_group *ng;
2871
2872 /*
2873 * The p->mm->numa_scan_seq field gets updated without
2874 * exclusive access. Use READ_ONCE() here to ensure
2875 * that the field is read in a single access:
2876 */
2877 seq = READ_ONCE(p->mm->numa_scan_seq);
2878 if (p->numa_scan_seq == seq)
2879 return;
2880 p->numa_scan_seq = seq;
2881 p->numa_scan_period_max = task_scan_max(p);
2882
2883 total_faults = p->numa_faults_locality[0] +
2884 p->numa_faults_locality[1];
2885 runtime = numa_get_avg_runtime(p, &period);
2886
2887 /* If the task is part of a group prevent parallel updates to group stats */
2888 ng = deref_curr_numa_group(p);
2889 if (ng) {
2890 group_lock = &ng->lock;
2891 spin_lock_irq(group_lock);
2892 }
2893
2894 /* Find the node with the highest number of faults */
2895 for_each_online_node(nid) {
2896 /* Keep track of the offsets in numa_faults array */
2897 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2898 unsigned long faults = 0, group_faults = 0;
2899 int priv;
2900
2901 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2902 long diff, f_diff, f_weight;
2903
2904 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2905 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2906 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2907 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2908
2909 /* Decay existing window, copy faults since last scan */
2910 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2911 fault_types[priv] += p->numa_faults[membuf_idx];
2912 p->numa_faults[membuf_idx] = 0;
2913
2914 /*
2915 * Normalize the faults_from, so all tasks in a group
2916 * count according to CPU use, instead of by the raw
2917 * number of faults. Tasks with little runtime have
2918 * little over-all impact on throughput, and thus their
2919 * faults are less important.
2920 */
2921 f_weight = div64_u64(runtime << 16, period + 1);
2922 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2923 (total_faults + 1);
2924 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2925 p->numa_faults[cpubuf_idx] = 0;
2926
2927 p->numa_faults[mem_idx] += diff;
2928 p->numa_faults[cpu_idx] += f_diff;
2929 faults += p->numa_faults[mem_idx];
2930 p->total_numa_faults += diff;
2931 if (ng) {
2932 /*
2933 * safe because we can only change our own group
2934 *
2935 * mem_idx represents the offset for a given
2936 * nid and priv in a specific region because it
2937 * is at the beginning of the numa_faults array.
2938 */
2939 ng->faults[mem_idx] += diff;
2940 ng->faults[cpu_idx] += f_diff;
2941 ng->total_faults += diff;
2942 group_faults += ng->faults[mem_idx];
2943 }
2944 }
2945
2946 if (!ng) {
2947 if (faults > max_faults) {
2948 max_faults = faults;
2949 max_nid = nid;
2950 }
2951 } else if (group_faults > max_faults) {
2952 max_faults = group_faults;
2953 max_nid = nid;
2954 }
2955 }
2956
2957 /* Cannot migrate task to CPU-less node */
2958 max_nid = numa_nearest_node(max_nid, N_CPU);
2959
2960 if (ng) {
2961 numa_group_count_active_nodes(ng);
2962 spin_unlock_irq(group_lock);
2963 max_nid = preferred_group_nid(p, max_nid);
2964 }
2965
2966 if (max_faults) {
2967 /* Set the new preferred node */
2968 if (max_nid != p->numa_preferred_nid)
2969 sched_setnuma(p, max_nid);
2970 }
2971
2972 update_task_scan_period(p, fault_types[0], fault_types[1]);
2973 }
2974
get_numa_group(struct numa_group * grp)2975 static inline int get_numa_group(struct numa_group *grp)
2976 {
2977 return refcount_inc_not_zero(&grp->refcount);
2978 }
2979
put_numa_group(struct numa_group * grp)2980 static inline void put_numa_group(struct numa_group *grp)
2981 {
2982 if (refcount_dec_and_test(&grp->refcount))
2983 kfree_rcu(grp, rcu);
2984 }
2985
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)2986 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2987 int *priv)
2988 {
2989 struct numa_group *grp, *my_grp;
2990 struct task_struct *tsk;
2991 bool join = false;
2992 int cpu = cpupid_to_cpu(cpupid);
2993 int i;
2994
2995 if (unlikely(!deref_curr_numa_group(p))) {
2996 unsigned int size = sizeof(struct numa_group) +
2997 NR_NUMA_HINT_FAULT_STATS *
2998 nr_node_ids * sizeof(unsigned long);
2999
3000 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
3001 if (!grp)
3002 return;
3003
3004 refcount_set(&grp->refcount, 1);
3005 grp->active_nodes = 1;
3006 grp->max_faults_cpu = 0;
3007 spin_lock_init(&grp->lock);
3008 grp->gid = p->pid;
3009
3010 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3011 grp->faults[i] = p->numa_faults[i];
3012
3013 grp->total_faults = p->total_numa_faults;
3014
3015 grp->nr_tasks++;
3016 rcu_assign_pointer(p->numa_group, grp);
3017 }
3018
3019 rcu_read_lock();
3020 tsk = READ_ONCE(cpu_rq(cpu)->curr);
3021
3022 if (!cpupid_match_pid(tsk, cpupid))
3023 goto no_join;
3024
3025 grp = rcu_dereference(tsk->numa_group);
3026 if (!grp)
3027 goto no_join;
3028
3029 my_grp = deref_curr_numa_group(p);
3030 if (grp == my_grp)
3031 goto no_join;
3032
3033 /*
3034 * Only join the other group if its bigger; if we're the bigger group,
3035 * the other task will join us.
3036 */
3037 if (my_grp->nr_tasks > grp->nr_tasks)
3038 goto no_join;
3039
3040 /*
3041 * Tie-break on the grp address.
3042 */
3043 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3044 goto no_join;
3045
3046 /* Always join threads in the same process. */
3047 if (tsk->mm == current->mm)
3048 join = true;
3049
3050 /* Simple filter to avoid false positives due to PID collisions */
3051 if (flags & TNF_SHARED)
3052 join = true;
3053
3054 /* Update priv based on whether false sharing was detected */
3055 *priv = !join;
3056
3057 if (join && !get_numa_group(grp))
3058 goto no_join;
3059
3060 rcu_read_unlock();
3061
3062 if (!join)
3063 return;
3064
3065 WARN_ON_ONCE(irqs_disabled());
3066 double_lock_irq(&my_grp->lock, &grp->lock);
3067
3068 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3069 my_grp->faults[i] -= p->numa_faults[i];
3070 grp->faults[i] += p->numa_faults[i];
3071 }
3072 my_grp->total_faults -= p->total_numa_faults;
3073 grp->total_faults += p->total_numa_faults;
3074
3075 my_grp->nr_tasks--;
3076 grp->nr_tasks++;
3077
3078 spin_unlock(&my_grp->lock);
3079 spin_unlock_irq(&grp->lock);
3080
3081 rcu_assign_pointer(p->numa_group, grp);
3082
3083 put_numa_group(my_grp);
3084 return;
3085
3086 no_join:
3087 rcu_read_unlock();
3088 return;
3089 }
3090
3091 /*
3092 * Get rid of NUMA statistics associated with a task (either current or dead).
3093 * If @final is set, the task is dead and has reached refcount zero, so we can
3094 * safely free all relevant data structures. Otherwise, there might be
3095 * concurrent reads from places like load balancing and procfs, and we should
3096 * reset the data back to default state without freeing ->numa_faults.
3097 */
task_numa_free(struct task_struct * p,bool final)3098 void task_numa_free(struct task_struct *p, bool final)
3099 {
3100 /* safe: p either is current or is being freed by current */
3101 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3102 unsigned long *numa_faults = p->numa_faults;
3103 unsigned long flags;
3104 int i;
3105
3106 if (!numa_faults)
3107 return;
3108
3109 if (grp) {
3110 spin_lock_irqsave(&grp->lock, flags);
3111 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3112 grp->faults[i] -= p->numa_faults[i];
3113 grp->total_faults -= p->total_numa_faults;
3114
3115 grp->nr_tasks--;
3116 spin_unlock_irqrestore(&grp->lock, flags);
3117 RCU_INIT_POINTER(p->numa_group, NULL);
3118 put_numa_group(grp);
3119 }
3120
3121 if (final) {
3122 p->numa_faults = NULL;
3123 kfree(numa_faults);
3124 } else {
3125 p->total_numa_faults = 0;
3126 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3127 numa_faults[i] = 0;
3128 }
3129 }
3130
3131 /*
3132 * Got a PROT_NONE fault for a page on @node.
3133 */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3134 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3135 {
3136 struct task_struct *p = current;
3137 bool migrated = flags & TNF_MIGRATED;
3138 int cpu_node = task_node(current);
3139 int local = !!(flags & TNF_FAULT_LOCAL);
3140 struct numa_group *ng;
3141 int priv;
3142
3143 if (!static_branch_likely(&sched_numa_balancing))
3144 return;
3145
3146 /* for example, ksmd faulting in a user's mm */
3147 if (!p->mm)
3148 return;
3149
3150 /*
3151 * NUMA faults statistics are unnecessary for the slow memory
3152 * node for memory tiering mode.
3153 */
3154 if (!node_is_toptier(mem_node) &&
3155 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3156 !cpupid_valid(last_cpupid)))
3157 return;
3158
3159 /* Allocate buffer to track faults on a per-node basis */
3160 if (unlikely(!p->numa_faults)) {
3161 int size = sizeof(*p->numa_faults) *
3162 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3163
3164 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3165 if (!p->numa_faults)
3166 return;
3167
3168 p->total_numa_faults = 0;
3169 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3170 }
3171
3172 /*
3173 * First accesses are treated as private, otherwise consider accesses
3174 * to be private if the accessing pid has not changed
3175 */
3176 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3177 priv = 1;
3178 } else {
3179 priv = cpupid_match_pid(p, last_cpupid);
3180 if (!priv && !(flags & TNF_NO_GROUP))
3181 task_numa_group(p, last_cpupid, flags, &priv);
3182 }
3183
3184 /*
3185 * If a workload spans multiple NUMA nodes, a shared fault that
3186 * occurs wholly within the set of nodes that the workload is
3187 * actively using should be counted as local. This allows the
3188 * scan rate to slow down when a workload has settled down.
3189 */
3190 ng = deref_curr_numa_group(p);
3191 if (!priv && !local && ng && ng->active_nodes > 1 &&
3192 numa_is_active_node(cpu_node, ng) &&
3193 numa_is_active_node(mem_node, ng))
3194 local = 1;
3195
3196 /*
3197 * Retry to migrate task to preferred node periodically, in case it
3198 * previously failed, or the scheduler moved us.
3199 */
3200 if (time_after(jiffies, p->numa_migrate_retry)) {
3201 task_numa_placement(p);
3202 numa_migrate_preferred(p);
3203 }
3204
3205 if (migrated)
3206 p->numa_pages_migrated += pages;
3207 if (flags & TNF_MIGRATE_FAIL)
3208 p->numa_faults_locality[2] += pages;
3209
3210 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3211 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3212 p->numa_faults_locality[local] += pages;
3213 }
3214
reset_ptenuma_scan(struct task_struct * p)3215 static void reset_ptenuma_scan(struct task_struct *p)
3216 {
3217 /*
3218 * We only did a read acquisition of the mmap sem, so
3219 * p->mm->numa_scan_seq is written to without exclusive access
3220 * and the update is not guaranteed to be atomic. That's not
3221 * much of an issue though, since this is just used for
3222 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3223 * expensive, to avoid any form of compiler optimizations:
3224 */
3225 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3226 p->mm->numa_scan_offset = 0;
3227 }
3228
vma_is_accessed(struct mm_struct * mm,struct vm_area_struct * vma)3229 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma)
3230 {
3231 unsigned long pids;
3232 /*
3233 * Allow unconditional access first two times, so that all the (pages)
3234 * of VMAs get prot_none fault introduced irrespective of accesses.
3235 * This is also done to avoid any side effect of task scanning
3236 * amplifying the unfairness of disjoint set of VMAs' access.
3237 */
3238 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2)
3239 return true;
3240
3241 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1];
3242 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids))
3243 return true;
3244
3245 /*
3246 * Complete a scan that has already started regardless of PID access, or
3247 * some VMAs may never be scanned in multi-threaded applications:
3248 */
3249 if (mm->numa_scan_offset > vma->vm_start) {
3250 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID);
3251 return true;
3252 }
3253
3254 /*
3255 * This vma has not been accessed for a while, and if the number
3256 * the threads in the same process is low, which means no other
3257 * threads can help scan this vma, force a vma scan.
3258 */
3259 if (READ_ONCE(mm->numa_scan_seq) >
3260 (vma->numab_state->prev_scan_seq + get_nr_threads(current)))
3261 return true;
3262
3263 return false;
3264 }
3265
3266 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3267
3268 /*
3269 * The expensive part of numa migration is done from task_work context.
3270 * Triggered from task_tick_numa().
3271 */
task_numa_work(struct callback_head * work)3272 static void task_numa_work(struct callback_head *work)
3273 {
3274 unsigned long migrate, next_scan, now = jiffies;
3275 struct task_struct *p = current;
3276 struct mm_struct *mm = p->mm;
3277 u64 runtime = p->se.sum_exec_runtime;
3278 struct vm_area_struct *vma;
3279 unsigned long start, end;
3280 unsigned long nr_pte_updates = 0;
3281 long pages, virtpages;
3282 struct vma_iterator vmi;
3283 bool vma_pids_skipped;
3284 bool vma_pids_forced = false;
3285
3286 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
3287
3288 work->next = work;
3289 /*
3290 * Who cares about NUMA placement when they're dying.
3291 *
3292 * NOTE: make sure not to dereference p->mm before this check,
3293 * exit_task_work() happens _after_ exit_mm() so we could be called
3294 * without p->mm even though we still had it when we enqueued this
3295 * work.
3296 */
3297 if (p->flags & PF_EXITING)
3298 return;
3299
3300 /*
3301 * Memory is pinned to only one NUMA node via cpuset.mems, naturally
3302 * no page can be migrated.
3303 */
3304 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) {
3305 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed);
3306 return;
3307 }
3308
3309 if (!mm->numa_next_scan) {
3310 mm->numa_next_scan = now +
3311 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3312 }
3313
3314 /*
3315 * Enforce maximal scan/migration frequency..
3316 */
3317 migrate = mm->numa_next_scan;
3318 if (time_before(now, migrate))
3319 return;
3320
3321 if (p->numa_scan_period == 0) {
3322 p->numa_scan_period_max = task_scan_max(p);
3323 p->numa_scan_period = task_scan_start(p);
3324 }
3325
3326 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3327 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3328 return;
3329
3330 /*
3331 * Delay this task enough that another task of this mm will likely win
3332 * the next time around.
3333 */
3334 p->node_stamp += 2 * TICK_NSEC;
3335
3336 pages = sysctl_numa_balancing_scan_size;
3337 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3338 virtpages = pages * 8; /* Scan up to this much virtual space */
3339 if (!pages)
3340 return;
3341
3342
3343 if (!mmap_read_trylock(mm))
3344 return;
3345
3346 /*
3347 * VMAs are skipped if the current PID has not trapped a fault within
3348 * the VMA recently. Allow scanning to be forced if there is no
3349 * suitable VMA remaining.
3350 */
3351 vma_pids_skipped = false;
3352
3353 retry_pids:
3354 start = mm->numa_scan_offset;
3355 vma_iter_init(&vmi, mm, start);
3356 vma = vma_next(&vmi);
3357 if (!vma) {
3358 reset_ptenuma_scan(p);
3359 start = 0;
3360 vma_iter_set(&vmi, start);
3361 vma = vma_next(&vmi);
3362 }
3363
3364 for (; vma; vma = vma_next(&vmi)) {
3365 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3366 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3367 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE);
3368 continue;
3369 }
3370
3371 /*
3372 * Shared library pages mapped by multiple processes are not
3373 * migrated as it is expected they are cache replicated. Avoid
3374 * hinting faults in read-only file-backed mappings or the vDSO
3375 * as migrating the pages will be of marginal benefit.
3376 */
3377 if (!vma->vm_mm ||
3378 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) {
3379 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO);
3380 continue;
3381 }
3382
3383 /*
3384 * Skip inaccessible VMAs to avoid any confusion between
3385 * PROT_NONE and NUMA hinting PTEs
3386 */
3387 if (!vma_is_accessible(vma)) {
3388 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE);
3389 continue;
3390 }
3391
3392 /* Initialise new per-VMA NUMAB state. */
3393 if (!vma->numab_state) {
3394 struct vma_numab_state *ptr;
3395
3396 ptr = kzalloc(sizeof(*ptr), GFP_KERNEL);
3397 if (!ptr)
3398 continue;
3399
3400 if (cmpxchg(&vma->numab_state, NULL, ptr)) {
3401 kfree(ptr);
3402 continue;
3403 }
3404
3405 vma->numab_state->start_scan_seq = mm->numa_scan_seq;
3406
3407 vma->numab_state->next_scan = now +
3408 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3409
3410 /* Reset happens after 4 times scan delay of scan start */
3411 vma->numab_state->pids_active_reset = vma->numab_state->next_scan +
3412 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3413
3414 /*
3415 * Ensure prev_scan_seq does not match numa_scan_seq,
3416 * to prevent VMAs being skipped prematurely on the
3417 * first scan:
3418 */
3419 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1;
3420 }
3421
3422 /*
3423 * Scanning the VMAs of short lived tasks add more overhead. So
3424 * delay the scan for new VMAs.
3425 */
3426 if (mm->numa_scan_seq && time_before(jiffies,
3427 vma->numab_state->next_scan)) {
3428 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY);
3429 continue;
3430 }
3431
3432 /* RESET access PIDs regularly for old VMAs. */
3433 if (mm->numa_scan_seq &&
3434 time_after(jiffies, vma->numab_state->pids_active_reset)) {
3435 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset +
3436 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3437 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]);
3438 vma->numab_state->pids_active[1] = 0;
3439 }
3440
3441 /* Do not rescan VMAs twice within the same sequence. */
3442 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) {
3443 mm->numa_scan_offset = vma->vm_end;
3444 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED);
3445 continue;
3446 }
3447
3448 /*
3449 * Do not scan the VMA if task has not accessed it, unless no other
3450 * VMA candidate exists.
3451 */
3452 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) {
3453 vma_pids_skipped = true;
3454 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE);
3455 continue;
3456 }
3457
3458 do {
3459 start = max(start, vma->vm_start);
3460 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3461 end = min(end, vma->vm_end);
3462 nr_pte_updates = change_prot_numa(vma, start, end);
3463
3464 /*
3465 * Try to scan sysctl_numa_balancing_size worth of
3466 * hpages that have at least one present PTE that
3467 * is not already PTE-numa. If the VMA contains
3468 * areas that are unused or already full of prot_numa
3469 * PTEs, scan up to virtpages, to skip through those
3470 * areas faster.
3471 */
3472 if (nr_pte_updates)
3473 pages -= (end - start) >> PAGE_SHIFT;
3474 virtpages -= (end - start) >> PAGE_SHIFT;
3475
3476 start = end;
3477 if (pages <= 0 || virtpages <= 0)
3478 goto out;
3479
3480 cond_resched();
3481 } while (end != vma->vm_end);
3482
3483 /* VMA scan is complete, do not scan until next sequence. */
3484 vma->numab_state->prev_scan_seq = mm->numa_scan_seq;
3485
3486 /*
3487 * Only force scan within one VMA at a time, to limit the
3488 * cost of scanning a potentially uninteresting VMA.
3489 */
3490 if (vma_pids_forced)
3491 break;
3492 }
3493
3494 /*
3495 * If no VMAs are remaining and VMAs were skipped due to the PID
3496 * not accessing the VMA previously, then force a scan to ensure
3497 * forward progress:
3498 */
3499 if (!vma && !vma_pids_forced && vma_pids_skipped) {
3500 vma_pids_forced = true;
3501 goto retry_pids;
3502 }
3503
3504 out:
3505 /*
3506 * It is possible to reach the end of the VMA list but the last few
3507 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3508 * would find the !migratable VMA on the next scan but not reset the
3509 * scanner to the start so check it now.
3510 */
3511 if (vma)
3512 mm->numa_scan_offset = start;
3513 else
3514 reset_ptenuma_scan(p);
3515 mmap_read_unlock(mm);
3516
3517 /*
3518 * Make sure tasks use at least 32x as much time to run other code
3519 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3520 * Usually update_task_scan_period slows down scanning enough; on an
3521 * overloaded system we need to limit overhead on a per task basis.
3522 */
3523 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3524 u64 diff = p->se.sum_exec_runtime - runtime;
3525 p->node_stamp += 32 * diff;
3526 }
3527 }
3528
init_numa_balancing(u64 clone_flags,struct task_struct * p)3529 void init_numa_balancing(u64 clone_flags, struct task_struct *p)
3530 {
3531 int mm_users = 0;
3532 struct mm_struct *mm = p->mm;
3533
3534 if (mm) {
3535 mm_users = atomic_read(&mm->mm_users);
3536 if (mm_users == 1) {
3537 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3538 mm->numa_scan_seq = 0;
3539 }
3540 }
3541 p->node_stamp = 0;
3542 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3543 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3544 p->numa_migrate_retry = 0;
3545 /* Protect against double add, see task_tick_numa and task_numa_work */
3546 p->numa_work.next = &p->numa_work;
3547 p->numa_faults = NULL;
3548 p->numa_pages_migrated = 0;
3549 p->total_numa_faults = 0;
3550 RCU_INIT_POINTER(p->numa_group, NULL);
3551 p->last_task_numa_placement = 0;
3552 p->last_sum_exec_runtime = 0;
3553
3554 init_task_work(&p->numa_work, task_numa_work);
3555
3556 /* New address space, reset the preferred nid */
3557 if (!(clone_flags & CLONE_VM)) {
3558 p->numa_preferred_nid = NUMA_NO_NODE;
3559 return;
3560 }
3561
3562 /*
3563 * New thread, keep existing numa_preferred_nid which should be copied
3564 * already by arch_dup_task_struct but stagger when scans start.
3565 */
3566 if (mm) {
3567 unsigned int delay;
3568
3569 delay = min_t(unsigned int, task_scan_max(current),
3570 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3571 delay += 2 * TICK_NSEC;
3572 p->node_stamp = delay;
3573 }
3574 }
3575
3576 /*
3577 * Drive the periodic memory faults..
3578 */
task_tick_numa(struct rq * rq,struct task_struct * curr)3579 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3580 {
3581 struct callback_head *work = &curr->numa_work;
3582 u64 period, now;
3583
3584 /*
3585 * We don't care about NUMA placement if we don't have memory.
3586 */
3587 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3588 return;
3589
3590 /*
3591 * Using runtime rather than walltime has the dual advantage that
3592 * we (mostly) drive the selection from busy threads and that the
3593 * task needs to have done some actual work before we bother with
3594 * NUMA placement.
3595 */
3596 now = curr->se.sum_exec_runtime;
3597 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3598
3599 if (now > curr->node_stamp + period) {
3600 if (!curr->node_stamp)
3601 curr->numa_scan_period = task_scan_start(curr);
3602 curr->node_stamp += period;
3603
3604 if (!time_before(jiffies, curr->mm->numa_next_scan))
3605 task_work_add(curr, work, TWA_RESUME);
3606 }
3607 }
3608
update_scan_period(struct task_struct * p,int new_cpu)3609 static void update_scan_period(struct task_struct *p, int new_cpu)
3610 {
3611 int src_nid = cpu_to_node(task_cpu(p));
3612 int dst_nid = cpu_to_node(new_cpu);
3613
3614 if (!static_branch_likely(&sched_numa_balancing))
3615 return;
3616
3617 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3618 return;
3619
3620 if (src_nid == dst_nid)
3621 return;
3622
3623 /*
3624 * Allow resets if faults have been trapped before one scan
3625 * has completed. This is most likely due to a new task that
3626 * is pulled cross-node due to wakeups or load balancing.
3627 */
3628 if (p->numa_scan_seq) {
3629 /*
3630 * Avoid scan adjustments if moving to the preferred
3631 * node or if the task was not previously running on
3632 * the preferred node.
3633 */
3634 if (dst_nid == p->numa_preferred_nid ||
3635 (p->numa_preferred_nid != NUMA_NO_NODE &&
3636 src_nid != p->numa_preferred_nid))
3637 return;
3638 }
3639
3640 p->numa_scan_period = task_scan_start(p);
3641 }
3642
3643 #else /* !CONFIG_NUMA_BALANCING: */
3644
task_tick_numa(struct rq * rq,struct task_struct * curr)3645 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3646 {
3647 }
3648
account_numa_enqueue(struct rq * rq,struct task_struct * p)3649 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3650 {
3651 }
3652
account_numa_dequeue(struct rq * rq,struct task_struct * p)3653 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3654 {
3655 }
3656
update_scan_period(struct task_struct * p,int new_cpu)3657 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3658 {
3659 }
3660
3661 #endif /* !CONFIG_NUMA_BALANCING */
3662
3663 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3664 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3665 {
3666 update_load_add(&cfs_rq->load, se->load.weight);
3667 if (entity_is_task(se)) {
3668 struct rq *rq = rq_of(cfs_rq);
3669
3670 account_numa_enqueue(rq, task_of(se));
3671 list_add(&se->group_node, &rq->cfs_tasks);
3672 }
3673 cfs_rq->nr_queued++;
3674 }
3675
3676 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3677 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3678 {
3679 update_load_sub(&cfs_rq->load, se->load.weight);
3680 if (entity_is_task(se)) {
3681 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3682 list_del_init(&se->group_node);
3683 }
3684 cfs_rq->nr_queued--;
3685 }
3686
3687 /*
3688 * Signed add and clamp on underflow.
3689 *
3690 * Explicitly do a load-store to ensure the intermediate value never hits
3691 * memory. This allows lockless observations without ever seeing the negative
3692 * values.
3693 */
3694 #define add_positive(_ptr, _val) do { \
3695 typeof(_ptr) ptr = (_ptr); \
3696 typeof(_val) val = (_val); \
3697 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3698 \
3699 res = var + val; \
3700 \
3701 if (val < 0 && res > var) \
3702 res = 0; \
3703 \
3704 WRITE_ONCE(*ptr, res); \
3705 } while (0)
3706
3707 /*
3708 * Unsigned subtract and clamp on underflow.
3709 *
3710 * Explicitly do a load-store to ensure the intermediate value never hits
3711 * memory. This allows lockless observations without ever seeing the negative
3712 * values.
3713 */
3714 #define sub_positive(_ptr, _val) do { \
3715 typeof(_ptr) ptr = (_ptr); \
3716 typeof(*ptr) val = (_val); \
3717 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3718 res = var - val; \
3719 if (res > var) \
3720 res = 0; \
3721 WRITE_ONCE(*ptr, res); \
3722 } while (0)
3723
3724 /*
3725 * Remove and clamp on negative, from a local variable.
3726 *
3727 * A variant of sub_positive(), which does not use explicit load-store
3728 * and is thus optimized for local variable updates.
3729 */
3730 #define lsub_positive(_ptr, _val) do { \
3731 typeof(_ptr) ptr = (_ptr); \
3732 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3733 } while (0)
3734
3735 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3736 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3737 {
3738 cfs_rq->avg.load_avg += se->avg.load_avg;
3739 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3740 }
3741
3742 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3743 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3744 {
3745 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3746 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3747 /* See update_cfs_rq_load_avg() */
3748 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3749 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3750 }
3751
3752 static void place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags);
3753
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3754 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3755 unsigned long weight)
3756 {
3757 bool curr = cfs_rq->curr == se;
3758
3759 if (se->on_rq) {
3760 /* commit outstanding execution time */
3761 update_curr(cfs_rq);
3762 update_entity_lag(cfs_rq, se);
3763 se->deadline -= se->vruntime;
3764 se->rel_deadline = 1;
3765 cfs_rq->nr_queued--;
3766 if (!curr)
3767 __dequeue_entity(cfs_rq, se);
3768 update_load_sub(&cfs_rq->load, se->load.weight);
3769 }
3770 dequeue_load_avg(cfs_rq, se);
3771
3772 /*
3773 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3774 * we need to scale se->vlag when w_i changes.
3775 */
3776 se->vlag = div_s64(se->vlag * se->load.weight, weight);
3777 if (se->rel_deadline)
3778 se->deadline = div_s64(se->deadline * se->load.weight, weight);
3779
3780 update_load_set(&se->load, weight);
3781
3782 do {
3783 u32 divider = get_pelt_divider(&se->avg);
3784
3785 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3786 } while (0);
3787
3788 enqueue_load_avg(cfs_rq, se);
3789 if (se->on_rq) {
3790 place_entity(cfs_rq, se, 0);
3791 update_load_add(&cfs_rq->load, se->load.weight);
3792 if (!curr)
3793 __enqueue_entity(cfs_rq, se);
3794 cfs_rq->nr_queued++;
3795 }
3796 }
3797
reweight_task_fair(struct rq * rq,struct task_struct * p,const struct load_weight * lw)3798 static void reweight_task_fair(struct rq *rq, struct task_struct *p,
3799 const struct load_weight *lw)
3800 {
3801 struct sched_entity *se = &p->se;
3802 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3803 struct load_weight *load = &se->load;
3804
3805 reweight_entity(cfs_rq, se, lw->weight);
3806 load->inv_weight = lw->inv_weight;
3807 }
3808
3809 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3810
3811 #ifdef CONFIG_FAIR_GROUP_SCHED
3812 /*
3813 * All this does is approximate the hierarchical proportion which includes that
3814 * global sum we all love to hate.
3815 *
3816 * That is, the weight of a group entity, is the proportional share of the
3817 * group weight based on the group runqueue weights. That is:
3818 *
3819 * tg->weight * grq->load.weight
3820 * ge->load.weight = ----------------------------- (1)
3821 * \Sum grq->load.weight
3822 *
3823 * Now, because computing that sum is prohibitively expensive to compute (been
3824 * there, done that) we approximate it with this average stuff. The average
3825 * moves slower and therefore the approximation is cheaper and more stable.
3826 *
3827 * So instead of the above, we substitute:
3828 *
3829 * grq->load.weight -> grq->avg.load_avg (2)
3830 *
3831 * which yields the following:
3832 *
3833 * tg->weight * grq->avg.load_avg
3834 * ge->load.weight = ------------------------------ (3)
3835 * tg->load_avg
3836 *
3837 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3838 *
3839 * That is shares_avg, and it is right (given the approximation (2)).
3840 *
3841 * The problem with it is that because the average is slow -- it was designed
3842 * to be exactly that of course -- this leads to transients in boundary
3843 * conditions. In specific, the case where the group was idle and we start the
3844 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3845 * yielding bad latency etc..
3846 *
3847 * Now, in that special case (1) reduces to:
3848 *
3849 * tg->weight * grq->load.weight
3850 * ge->load.weight = ----------------------------- = tg->weight (4)
3851 * grp->load.weight
3852 *
3853 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3854 *
3855 * So what we do is modify our approximation (3) to approach (4) in the (near)
3856 * UP case, like:
3857 *
3858 * ge->load.weight =
3859 *
3860 * tg->weight * grq->load.weight
3861 * --------------------------------------------------- (5)
3862 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3863 *
3864 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3865 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3866 *
3867 *
3868 * tg->weight * grq->load.weight
3869 * ge->load.weight = ----------------------------- (6)
3870 * tg_load_avg'
3871 *
3872 * Where:
3873 *
3874 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3875 * max(grq->load.weight, grq->avg.load_avg)
3876 *
3877 * And that is shares_weight and is icky. In the (near) UP case it approaches
3878 * (4) while in the normal case it approaches (3). It consistently
3879 * overestimates the ge->load.weight and therefore:
3880 *
3881 * \Sum ge->load.weight >= tg->weight
3882 *
3883 * hence icky!
3884 */
calc_group_shares(struct cfs_rq * cfs_rq)3885 static long calc_group_shares(struct cfs_rq *cfs_rq)
3886 {
3887 long tg_weight, tg_shares, load, shares;
3888 struct task_group *tg = cfs_rq->tg;
3889
3890 tg_shares = READ_ONCE(tg->shares);
3891
3892 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3893
3894 tg_weight = atomic_long_read(&tg->load_avg);
3895
3896 /* Ensure tg_weight >= load */
3897 tg_weight -= cfs_rq->tg_load_avg_contrib;
3898 tg_weight += load;
3899
3900 shares = (tg_shares * load);
3901 if (tg_weight)
3902 shares /= tg_weight;
3903
3904 /*
3905 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3906 * of a group with small tg->shares value. It is a floor value which is
3907 * assigned as a minimum load.weight to the sched_entity representing
3908 * the group on a CPU.
3909 *
3910 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3911 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3912 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3913 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3914 * instead of 0.
3915 */
3916 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3917 }
3918
3919 /*
3920 * Recomputes the group entity based on the current state of its group
3921 * runqueue.
3922 */
update_cfs_group(struct sched_entity * se)3923 static void update_cfs_group(struct sched_entity *se)
3924 {
3925 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3926 long shares;
3927
3928 /*
3929 * When a group becomes empty, preserve its weight. This matters for
3930 * DELAY_DEQUEUE.
3931 */
3932 if (!gcfs_rq || !gcfs_rq->load.weight)
3933 return;
3934
3935 shares = calc_group_shares(gcfs_rq);
3936 if (unlikely(se->load.weight != shares))
3937 reweight_entity(cfs_rq_of(se), se, shares);
3938 }
3939
3940 #else /* !CONFIG_FAIR_GROUP_SCHED: */
update_cfs_group(struct sched_entity * se)3941 static inline void update_cfs_group(struct sched_entity *se)
3942 {
3943 }
3944 #endif /* !CONFIG_FAIR_GROUP_SCHED */
3945
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)3946 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3947 {
3948 struct rq *rq = rq_of(cfs_rq);
3949
3950 if (&rq->cfs == cfs_rq) {
3951 /*
3952 * There are a few boundary cases this might miss but it should
3953 * get called often enough that that should (hopefully) not be
3954 * a real problem.
3955 *
3956 * It will not get called when we go idle, because the idle
3957 * thread is a different class (!fair), nor will the utilization
3958 * number include things like RT tasks.
3959 *
3960 * As is, the util number is not freq-invariant (we'd have to
3961 * implement arch_scale_freq_capacity() for that).
3962 *
3963 * See cpu_util_cfs().
3964 */
3965 cpufreq_update_util(rq, flags);
3966 }
3967 }
3968
load_avg_is_decayed(struct sched_avg * sa)3969 static inline bool load_avg_is_decayed(struct sched_avg *sa)
3970 {
3971 if (sa->load_sum)
3972 return false;
3973
3974 if (sa->util_sum)
3975 return false;
3976
3977 if (sa->runnable_sum)
3978 return false;
3979
3980 /*
3981 * _avg must be null when _sum are null because _avg = _sum / divider
3982 * Make sure that rounding and/or propagation of PELT values never
3983 * break this.
3984 */
3985 WARN_ON_ONCE(sa->load_avg ||
3986 sa->util_avg ||
3987 sa->runnable_avg);
3988
3989 return true;
3990 }
3991
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)3992 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
3993 {
3994 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
3995 cfs_rq->last_update_time_copy);
3996 }
3997 #ifdef CONFIG_FAIR_GROUP_SCHED
3998 /*
3999 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4000 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4001 * bottom-up, we only have to test whether the cfs_rq before us on the list
4002 * is our child.
4003 * If cfs_rq is not on the list, test whether a child needs its to be added to
4004 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
4005 */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4006 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4007 {
4008 struct cfs_rq *prev_cfs_rq;
4009 struct list_head *prev;
4010 struct rq *rq = rq_of(cfs_rq);
4011
4012 if (cfs_rq->on_list) {
4013 prev = cfs_rq->leaf_cfs_rq_list.prev;
4014 } else {
4015 prev = rq->tmp_alone_branch;
4016 }
4017
4018 if (prev == &rq->leaf_cfs_rq_list)
4019 return false;
4020
4021 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4022
4023 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4024 }
4025
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4026 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4027 {
4028 if (cfs_rq->load.weight)
4029 return false;
4030
4031 if (!load_avg_is_decayed(&cfs_rq->avg))
4032 return false;
4033
4034 if (child_cfs_rq_on_list(cfs_rq))
4035 return false;
4036
4037 return true;
4038 }
4039
4040 /**
4041 * update_tg_load_avg - update the tg's load avg
4042 * @cfs_rq: the cfs_rq whose avg changed
4043 *
4044 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4045 * However, because tg->load_avg is a global value there are performance
4046 * considerations.
4047 *
4048 * In order to avoid having to look at the other cfs_rq's, we use a
4049 * differential update where we store the last value we propagated. This in
4050 * turn allows skipping updates if the differential is 'small'.
4051 *
4052 * Updating tg's load_avg is necessary before update_cfs_share().
4053 */
update_tg_load_avg(struct cfs_rq * cfs_rq)4054 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4055 {
4056 long delta;
4057 u64 now;
4058
4059 /*
4060 * No need to update load_avg for root_task_group as it is not used.
4061 */
4062 if (cfs_rq->tg == &root_task_group)
4063 return;
4064
4065 /* rq has been offline and doesn't contribute to the share anymore: */
4066 if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4067 return;
4068
4069 /*
4070 * For migration heavy workloads, access to tg->load_avg can be
4071 * unbound. Limit the update rate to at most once per ms.
4072 */
4073 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4074 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4075 return;
4076
4077 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4078 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4079 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4080 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4081 cfs_rq->last_update_tg_load_avg = now;
4082 }
4083 }
4084
clear_tg_load_avg(struct cfs_rq * cfs_rq)4085 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4086 {
4087 long delta;
4088 u64 now;
4089
4090 /*
4091 * No need to update load_avg for root_task_group, as it is not used.
4092 */
4093 if (cfs_rq->tg == &root_task_group)
4094 return;
4095
4096 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4097 delta = 0 - cfs_rq->tg_load_avg_contrib;
4098 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4099 cfs_rq->tg_load_avg_contrib = 0;
4100 cfs_rq->last_update_tg_load_avg = now;
4101 }
4102
4103 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)4104 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4105 {
4106 struct task_group *tg;
4107
4108 lockdep_assert_rq_held(rq);
4109
4110 /*
4111 * The rq clock has already been updated in
4112 * set_rq_offline(), so we should skip updating
4113 * the rq clock again in unthrottle_cfs_rq().
4114 */
4115 rq_clock_start_loop_update(rq);
4116
4117 rcu_read_lock();
4118 list_for_each_entry_rcu(tg, &task_groups, list) {
4119 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4120
4121 clear_tg_load_avg(cfs_rq);
4122 }
4123 rcu_read_unlock();
4124
4125 rq_clock_stop_loop_update(rq);
4126 }
4127
4128 /*
4129 * Called within set_task_rq() right before setting a task's CPU. The
4130 * caller only guarantees p->pi_lock is held; no other assumptions,
4131 * including the state of rq->lock, should be made.
4132 */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4133 void set_task_rq_fair(struct sched_entity *se,
4134 struct cfs_rq *prev, struct cfs_rq *next)
4135 {
4136 u64 p_last_update_time;
4137 u64 n_last_update_time;
4138
4139 if (!sched_feat(ATTACH_AGE_LOAD))
4140 return;
4141
4142 /*
4143 * We are supposed to update the task to "current" time, then its up to
4144 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4145 * getting what current time is, so simply throw away the out-of-date
4146 * time. This will result in the wakee task is less decayed, but giving
4147 * the wakee more load sounds not bad.
4148 */
4149 if (!(se->avg.last_update_time && prev))
4150 return;
4151
4152 p_last_update_time = cfs_rq_last_update_time(prev);
4153 n_last_update_time = cfs_rq_last_update_time(next);
4154
4155 __update_load_avg_blocked_se(p_last_update_time, se);
4156 se->avg.last_update_time = n_last_update_time;
4157 }
4158
4159 /*
4160 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4161 * propagate its contribution. The key to this propagation is the invariant
4162 * that for each group:
4163 *
4164 * ge->avg == grq->avg (1)
4165 *
4166 * _IFF_ we look at the pure running and runnable sums. Because they
4167 * represent the very same entity, just at different points in the hierarchy.
4168 *
4169 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4170 * and simply copies the running/runnable sum over (but still wrong, because
4171 * the group entity and group rq do not have their PELT windows aligned).
4172 *
4173 * However, update_tg_cfs_load() is more complex. So we have:
4174 *
4175 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4176 *
4177 * And since, like util, the runnable part should be directly transferable,
4178 * the following would _appear_ to be the straight forward approach:
4179 *
4180 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4181 *
4182 * And per (1) we have:
4183 *
4184 * ge->avg.runnable_avg == grq->avg.runnable_avg
4185 *
4186 * Which gives:
4187 *
4188 * ge->load.weight * grq->avg.load_avg
4189 * ge->avg.load_avg = ----------------------------------- (4)
4190 * grq->load.weight
4191 *
4192 * Except that is wrong!
4193 *
4194 * Because while for entities historical weight is not important and we
4195 * really only care about our future and therefore can consider a pure
4196 * runnable sum, runqueues can NOT do this.
4197 *
4198 * We specifically want runqueues to have a load_avg that includes
4199 * historical weights. Those represent the blocked load, the load we expect
4200 * to (shortly) return to us. This only works by keeping the weights as
4201 * integral part of the sum. We therefore cannot decompose as per (3).
4202 *
4203 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4204 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4205 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4206 * runnable section of these tasks overlap (or not). If they were to perfectly
4207 * align the rq as a whole would be runnable 2/3 of the time. If however we
4208 * always have at least 1 runnable task, the rq as a whole is always runnable.
4209 *
4210 * So we'll have to approximate.. :/
4211 *
4212 * Given the constraint:
4213 *
4214 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4215 *
4216 * We can construct a rule that adds runnable to a rq by assuming minimal
4217 * overlap.
4218 *
4219 * On removal, we'll assume each task is equally runnable; which yields:
4220 *
4221 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4222 *
4223 * XXX: only do this for the part of runnable > running ?
4224 *
4225 */
4226 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4227 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4228 {
4229 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4230 u32 new_sum, divider;
4231
4232 /* Nothing to update */
4233 if (!delta_avg)
4234 return;
4235
4236 /*
4237 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4238 * See ___update_load_avg() for details.
4239 */
4240 divider = get_pelt_divider(&cfs_rq->avg);
4241
4242
4243 /* Set new sched_entity's utilization */
4244 se->avg.util_avg = gcfs_rq->avg.util_avg;
4245 new_sum = se->avg.util_avg * divider;
4246 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4247 se->avg.util_sum = new_sum;
4248
4249 /* Update parent cfs_rq utilization */
4250 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4251 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4252
4253 /* See update_cfs_rq_load_avg() */
4254 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4255 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4256 }
4257
4258 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4259 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4260 {
4261 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4262 u32 new_sum, divider;
4263
4264 /* Nothing to update */
4265 if (!delta_avg)
4266 return;
4267
4268 /*
4269 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4270 * See ___update_load_avg() for details.
4271 */
4272 divider = get_pelt_divider(&cfs_rq->avg);
4273
4274 /* Set new sched_entity's runnable */
4275 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4276 new_sum = se->avg.runnable_avg * divider;
4277 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4278 se->avg.runnable_sum = new_sum;
4279
4280 /* Update parent cfs_rq runnable */
4281 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4282 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4283 /* See update_cfs_rq_load_avg() */
4284 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4285 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4286 }
4287
4288 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4289 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4290 {
4291 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4292 unsigned long load_avg;
4293 u64 load_sum = 0;
4294 s64 delta_sum;
4295 u32 divider;
4296
4297 if (!runnable_sum)
4298 return;
4299
4300 gcfs_rq->prop_runnable_sum = 0;
4301
4302 /*
4303 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4304 * See ___update_load_avg() for details.
4305 */
4306 divider = get_pelt_divider(&cfs_rq->avg);
4307
4308 if (runnable_sum >= 0) {
4309 /*
4310 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4311 * the CPU is saturated running == runnable.
4312 */
4313 runnable_sum += se->avg.load_sum;
4314 runnable_sum = min_t(long, runnable_sum, divider);
4315 } else {
4316 /*
4317 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4318 * assuming all tasks are equally runnable.
4319 */
4320 if (scale_load_down(gcfs_rq->load.weight)) {
4321 load_sum = div_u64(gcfs_rq->avg.load_sum,
4322 scale_load_down(gcfs_rq->load.weight));
4323 }
4324
4325 /* But make sure to not inflate se's runnable */
4326 runnable_sum = min(se->avg.load_sum, load_sum);
4327 }
4328
4329 /*
4330 * runnable_sum can't be lower than running_sum
4331 * Rescale running sum to be in the same range as runnable sum
4332 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4333 * runnable_sum is in [0 : LOAD_AVG_MAX]
4334 */
4335 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4336 runnable_sum = max(runnable_sum, running_sum);
4337
4338 load_sum = se_weight(se) * runnable_sum;
4339 load_avg = div_u64(load_sum, divider);
4340
4341 delta_avg = load_avg - se->avg.load_avg;
4342 if (!delta_avg)
4343 return;
4344
4345 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4346
4347 se->avg.load_sum = runnable_sum;
4348 se->avg.load_avg = load_avg;
4349 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4350 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4351 /* See update_cfs_rq_load_avg() */
4352 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4353 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4354 }
4355
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4356 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4357 {
4358 cfs_rq->propagate = 1;
4359 cfs_rq->prop_runnable_sum += runnable_sum;
4360 }
4361
4362 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4363 static inline int propagate_entity_load_avg(struct sched_entity *se)
4364 {
4365 struct cfs_rq *cfs_rq, *gcfs_rq;
4366
4367 if (entity_is_task(se))
4368 return 0;
4369
4370 gcfs_rq = group_cfs_rq(se);
4371 if (!gcfs_rq->propagate)
4372 return 0;
4373
4374 gcfs_rq->propagate = 0;
4375
4376 cfs_rq = cfs_rq_of(se);
4377
4378 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4379
4380 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4381 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4382 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4383
4384 trace_pelt_cfs_tp(cfs_rq);
4385 trace_pelt_se_tp(se);
4386
4387 return 1;
4388 }
4389
4390 /*
4391 * Check if we need to update the load and the utilization of a blocked
4392 * group_entity:
4393 */
skip_blocked_update(struct sched_entity * se)4394 static inline bool skip_blocked_update(struct sched_entity *se)
4395 {
4396 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4397
4398 /*
4399 * If sched_entity still have not zero load or utilization, we have to
4400 * decay it:
4401 */
4402 if (se->avg.load_avg || se->avg.util_avg)
4403 return false;
4404
4405 /*
4406 * If there is a pending propagation, we have to update the load and
4407 * the utilization of the sched_entity:
4408 */
4409 if (gcfs_rq->propagate)
4410 return false;
4411
4412 /*
4413 * Otherwise, the load and the utilization of the sched_entity is
4414 * already zero and there is no pending propagation, so it will be a
4415 * waste of time to try to decay it:
4416 */
4417 return true;
4418 }
4419
4420 #else /* !CONFIG_FAIR_GROUP_SCHED: */
4421
update_tg_load_avg(struct cfs_rq * cfs_rq)4422 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4423
clear_tg_offline_cfs_rqs(struct rq * rq)4424 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4425
propagate_entity_load_avg(struct sched_entity * se)4426 static inline int propagate_entity_load_avg(struct sched_entity *se)
4427 {
4428 return 0;
4429 }
4430
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4431 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4432
4433 #endif /* !CONFIG_FAIR_GROUP_SCHED */
4434
4435 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4436 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4437 {
4438 u64 throttled = 0, now, lut;
4439 struct cfs_rq *cfs_rq;
4440 struct rq *rq;
4441 bool is_idle;
4442
4443 if (load_avg_is_decayed(&se->avg))
4444 return;
4445
4446 cfs_rq = cfs_rq_of(se);
4447 rq = rq_of(cfs_rq);
4448
4449 rcu_read_lock();
4450 is_idle = is_idle_task(rcu_dereference(rq->curr));
4451 rcu_read_unlock();
4452
4453 /*
4454 * The lag estimation comes with a cost we don't want to pay all the
4455 * time. Hence, limiting to the case where the source CPU is idle and
4456 * we know we are at the greatest risk to have an outdated clock.
4457 */
4458 if (!is_idle)
4459 return;
4460
4461 /*
4462 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4463 *
4464 * last_update_time (the cfs_rq's last_update_time)
4465 * = cfs_rq_clock_pelt()@cfs_rq_idle
4466 * = rq_clock_pelt()@cfs_rq_idle
4467 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4468 *
4469 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4470 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4471 *
4472 * rq_idle_lag (delta between now and rq's update)
4473 * = sched_clock_cpu() - rq_clock()@rq_idle
4474 *
4475 * We can then write:
4476 *
4477 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4478 * sched_clock_cpu() - rq_clock()@rq_idle
4479 * Where:
4480 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4481 * rq_clock()@rq_idle is rq->clock_idle
4482 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4483 * is cfs_rq->throttled_pelt_idle
4484 */
4485
4486 #ifdef CONFIG_CFS_BANDWIDTH
4487 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4488 /* The clock has been stopped for throttling */
4489 if (throttled == U64_MAX)
4490 return;
4491 #endif
4492 now = u64_u32_load(rq->clock_pelt_idle);
4493 /*
4494 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4495 * is observed the old clock_pelt_idle value and the new clock_idle,
4496 * which lead to an underestimation. The opposite would lead to an
4497 * overestimation.
4498 */
4499 smp_rmb();
4500 lut = cfs_rq_last_update_time(cfs_rq);
4501
4502 now -= throttled;
4503 if (now < lut)
4504 /*
4505 * cfs_rq->avg.last_update_time is more recent than our
4506 * estimation, let's use it.
4507 */
4508 now = lut;
4509 else
4510 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4511
4512 __update_load_avg_blocked_se(now, se);
4513 }
4514 #else /* !CONFIG_NO_HZ_COMMON: */
migrate_se_pelt_lag(struct sched_entity * se)4515 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4516 #endif /* !CONFIG_NO_HZ_COMMON */
4517
4518 /**
4519 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4520 * @now: current time, as per cfs_rq_clock_pelt()
4521 * @cfs_rq: cfs_rq to update
4522 *
4523 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4524 * avg. The immediate corollary is that all (fair) tasks must be attached.
4525 *
4526 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4527 *
4528 * Return: true if the load decayed or we removed load.
4529 *
4530 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4531 * call update_tg_load_avg() when this function returns true.
4532 */
4533 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4534 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4535 {
4536 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4537 struct sched_avg *sa = &cfs_rq->avg;
4538 int decayed = 0;
4539
4540 if (cfs_rq->removed.nr) {
4541 unsigned long r;
4542 u32 divider = get_pelt_divider(&cfs_rq->avg);
4543
4544 raw_spin_lock(&cfs_rq->removed.lock);
4545 swap(cfs_rq->removed.util_avg, removed_util);
4546 swap(cfs_rq->removed.load_avg, removed_load);
4547 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4548 cfs_rq->removed.nr = 0;
4549 raw_spin_unlock(&cfs_rq->removed.lock);
4550
4551 r = removed_load;
4552 sub_positive(&sa->load_avg, r);
4553 sub_positive(&sa->load_sum, r * divider);
4554 /* See sa->util_sum below */
4555 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4556
4557 r = removed_util;
4558 sub_positive(&sa->util_avg, r);
4559 sub_positive(&sa->util_sum, r * divider);
4560 /*
4561 * Because of rounding, se->util_sum might ends up being +1 more than
4562 * cfs->util_sum. Although this is not a problem by itself, detaching
4563 * a lot of tasks with the rounding problem between 2 updates of
4564 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4565 * cfs_util_avg is not.
4566 * Check that util_sum is still above its lower bound for the new
4567 * util_avg. Given that period_contrib might have moved since the last
4568 * sync, we are only sure that util_sum must be above or equal to
4569 * util_avg * minimum possible divider
4570 */
4571 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4572
4573 r = removed_runnable;
4574 sub_positive(&sa->runnable_avg, r);
4575 sub_positive(&sa->runnable_sum, r * divider);
4576 /* See sa->util_sum above */
4577 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4578 sa->runnable_avg * PELT_MIN_DIVIDER);
4579
4580 /*
4581 * removed_runnable is the unweighted version of removed_load so we
4582 * can use it to estimate removed_load_sum.
4583 */
4584 add_tg_cfs_propagate(cfs_rq,
4585 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4586
4587 decayed = 1;
4588 }
4589
4590 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4591 u64_u32_store_copy(sa->last_update_time,
4592 cfs_rq->last_update_time_copy,
4593 sa->last_update_time);
4594 return decayed;
4595 }
4596
4597 /**
4598 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4599 * @cfs_rq: cfs_rq to attach to
4600 * @se: sched_entity to attach
4601 *
4602 * Must call update_cfs_rq_load_avg() before this, since we rely on
4603 * cfs_rq->avg.last_update_time being current.
4604 */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4605 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4606 {
4607 /*
4608 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4609 * See ___update_load_avg() for details.
4610 */
4611 u32 divider = get_pelt_divider(&cfs_rq->avg);
4612
4613 /*
4614 * When we attach the @se to the @cfs_rq, we must align the decay
4615 * window because without that, really weird and wonderful things can
4616 * happen.
4617 *
4618 * XXX illustrate
4619 */
4620 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4621 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4622
4623 /*
4624 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4625 * period_contrib. This isn't strictly correct, but since we're
4626 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4627 * _sum a little.
4628 */
4629 se->avg.util_sum = se->avg.util_avg * divider;
4630
4631 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4632
4633 se->avg.load_sum = se->avg.load_avg * divider;
4634 if (se_weight(se) < se->avg.load_sum)
4635 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4636 else
4637 se->avg.load_sum = 1;
4638
4639 enqueue_load_avg(cfs_rq, se);
4640 cfs_rq->avg.util_avg += se->avg.util_avg;
4641 cfs_rq->avg.util_sum += se->avg.util_sum;
4642 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4643 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4644
4645 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4646
4647 cfs_rq_util_change(cfs_rq, 0);
4648
4649 trace_pelt_cfs_tp(cfs_rq);
4650 }
4651
4652 /**
4653 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4654 * @cfs_rq: cfs_rq to detach from
4655 * @se: sched_entity to detach
4656 *
4657 * Must call update_cfs_rq_load_avg() before this, since we rely on
4658 * cfs_rq->avg.last_update_time being current.
4659 */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4660 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4661 {
4662 dequeue_load_avg(cfs_rq, se);
4663 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4664 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4665 /* See update_cfs_rq_load_avg() */
4666 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4667 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4668
4669 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4670 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4671 /* See update_cfs_rq_load_avg() */
4672 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4673 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4674
4675 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4676
4677 cfs_rq_util_change(cfs_rq, 0);
4678
4679 trace_pelt_cfs_tp(cfs_rq);
4680 }
4681
4682 /*
4683 * Optional action to be done while updating the load average
4684 */
4685 #define UPDATE_TG 0x1
4686 #define SKIP_AGE_LOAD 0x2
4687 #define DO_ATTACH 0x4
4688 #define DO_DETACH 0x8
4689
4690 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4691 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4692 {
4693 u64 now = cfs_rq_clock_pelt(cfs_rq);
4694 int decayed;
4695
4696 /*
4697 * Track task load average for carrying it to new CPU after migrated, and
4698 * track group sched_entity load average for task_h_load calculation in migration
4699 */
4700 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4701 __update_load_avg_se(now, cfs_rq, se);
4702
4703 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4704 decayed |= propagate_entity_load_avg(se);
4705
4706 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4707
4708 /*
4709 * DO_ATTACH means we're here from enqueue_entity().
4710 * !last_update_time means we've passed through
4711 * migrate_task_rq_fair() indicating we migrated.
4712 *
4713 * IOW we're enqueueing a task on a new CPU.
4714 */
4715 attach_entity_load_avg(cfs_rq, se);
4716 update_tg_load_avg(cfs_rq);
4717
4718 } else if (flags & DO_DETACH) {
4719 /*
4720 * DO_DETACH means we're here from dequeue_entity()
4721 * and we are migrating task out of the CPU.
4722 */
4723 detach_entity_load_avg(cfs_rq, se);
4724 update_tg_load_avg(cfs_rq);
4725 } else if (decayed) {
4726 cfs_rq_util_change(cfs_rq, 0);
4727
4728 if (flags & UPDATE_TG)
4729 update_tg_load_avg(cfs_rq);
4730 }
4731 }
4732
4733 /*
4734 * Synchronize entity load avg of dequeued entity without locking
4735 * the previous rq.
4736 */
sync_entity_load_avg(struct sched_entity * se)4737 static void sync_entity_load_avg(struct sched_entity *se)
4738 {
4739 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4740 u64 last_update_time;
4741
4742 last_update_time = cfs_rq_last_update_time(cfs_rq);
4743 __update_load_avg_blocked_se(last_update_time, se);
4744 }
4745
4746 /*
4747 * Task first catches up with cfs_rq, and then subtract
4748 * itself from the cfs_rq (task must be off the queue now).
4749 */
remove_entity_load_avg(struct sched_entity * se)4750 static void remove_entity_load_avg(struct sched_entity *se)
4751 {
4752 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4753 unsigned long flags;
4754
4755 /*
4756 * tasks cannot exit without having gone through wake_up_new_task() ->
4757 * enqueue_task_fair() which will have added things to the cfs_rq,
4758 * so we can remove unconditionally.
4759 */
4760
4761 sync_entity_load_avg(se);
4762
4763 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4764 ++cfs_rq->removed.nr;
4765 cfs_rq->removed.util_avg += se->avg.util_avg;
4766 cfs_rq->removed.load_avg += se->avg.load_avg;
4767 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4768 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4769 }
4770
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4771 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4772 {
4773 return cfs_rq->avg.runnable_avg;
4774 }
4775
cfs_rq_load_avg(struct cfs_rq * cfs_rq)4776 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4777 {
4778 return cfs_rq->avg.load_avg;
4779 }
4780
4781 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
4782
task_util(struct task_struct * p)4783 static inline unsigned long task_util(struct task_struct *p)
4784 {
4785 return READ_ONCE(p->se.avg.util_avg);
4786 }
4787
task_runnable(struct task_struct * p)4788 static inline unsigned long task_runnable(struct task_struct *p)
4789 {
4790 return READ_ONCE(p->se.avg.runnable_avg);
4791 }
4792
_task_util_est(struct task_struct * p)4793 static inline unsigned long _task_util_est(struct task_struct *p)
4794 {
4795 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
4796 }
4797
task_util_est(struct task_struct * p)4798 static inline unsigned long task_util_est(struct task_struct *p)
4799 {
4800 return max(task_util(p), _task_util_est(p));
4801 }
4802
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4803 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4804 struct task_struct *p)
4805 {
4806 unsigned int enqueued;
4807
4808 if (!sched_feat(UTIL_EST))
4809 return;
4810
4811 /* Update root cfs_rq's estimated utilization */
4812 enqueued = cfs_rq->avg.util_est;
4813 enqueued += _task_util_est(p);
4814 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4815
4816 trace_sched_util_est_cfs_tp(cfs_rq);
4817 }
4818
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4819 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4820 struct task_struct *p)
4821 {
4822 unsigned int enqueued;
4823
4824 if (!sched_feat(UTIL_EST))
4825 return;
4826
4827 /* Update root cfs_rq's estimated utilization */
4828 enqueued = cfs_rq->avg.util_est;
4829 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4830 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4831
4832 trace_sched_util_est_cfs_tp(cfs_rq);
4833 }
4834
4835 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4836
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4837 static inline void util_est_update(struct cfs_rq *cfs_rq,
4838 struct task_struct *p,
4839 bool task_sleep)
4840 {
4841 unsigned int ewma, dequeued, last_ewma_diff;
4842
4843 if (!sched_feat(UTIL_EST))
4844 return;
4845
4846 /*
4847 * Skip update of task's estimated utilization when the task has not
4848 * yet completed an activation, e.g. being migrated.
4849 */
4850 if (!task_sleep)
4851 return;
4852
4853 /* Get current estimate of utilization */
4854 ewma = READ_ONCE(p->se.avg.util_est);
4855
4856 /*
4857 * If the PELT values haven't changed since enqueue time,
4858 * skip the util_est update.
4859 */
4860 if (ewma & UTIL_AVG_UNCHANGED)
4861 return;
4862
4863 /* Get utilization at dequeue */
4864 dequeued = task_util(p);
4865
4866 /*
4867 * Reset EWMA on utilization increases, the moving average is used only
4868 * to smooth utilization decreases.
4869 */
4870 if (ewma <= dequeued) {
4871 ewma = dequeued;
4872 goto done;
4873 }
4874
4875 /*
4876 * Skip update of task's estimated utilization when its members are
4877 * already ~1% close to its last activation value.
4878 */
4879 last_ewma_diff = ewma - dequeued;
4880 if (last_ewma_diff < UTIL_EST_MARGIN)
4881 goto done;
4882
4883 /*
4884 * To avoid underestimate of task utilization, skip updates of EWMA if
4885 * we cannot grant that thread got all CPU time it wanted.
4886 */
4887 if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
4888 goto done;
4889
4890
4891 /*
4892 * Update Task's estimated utilization
4893 *
4894 * When *p completes an activation we can consolidate another sample
4895 * of the task size. This is done by using this value to update the
4896 * Exponential Weighted Moving Average (EWMA):
4897 *
4898 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4899 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4900 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4901 * = w * ( -last_ewma_diff ) + ewma(t-1)
4902 * = w * (-last_ewma_diff + ewma(t-1) / w)
4903 *
4904 * Where 'w' is the weight of new samples, which is configured to be
4905 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4906 */
4907 ewma <<= UTIL_EST_WEIGHT_SHIFT;
4908 ewma -= last_ewma_diff;
4909 ewma >>= UTIL_EST_WEIGHT_SHIFT;
4910 done:
4911 ewma |= UTIL_AVG_UNCHANGED;
4912 WRITE_ONCE(p->se.avg.util_est, ewma);
4913
4914 trace_sched_util_est_se_tp(&p->se);
4915 }
4916
get_actual_cpu_capacity(int cpu)4917 static inline unsigned long get_actual_cpu_capacity(int cpu)
4918 {
4919 unsigned long capacity = arch_scale_cpu_capacity(cpu);
4920
4921 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
4922
4923 return capacity;
4924 }
4925
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)4926 static inline int util_fits_cpu(unsigned long util,
4927 unsigned long uclamp_min,
4928 unsigned long uclamp_max,
4929 int cpu)
4930 {
4931 unsigned long capacity = capacity_of(cpu);
4932 unsigned long capacity_orig;
4933 bool fits, uclamp_max_fits;
4934
4935 /*
4936 * Check if the real util fits without any uclamp boost/cap applied.
4937 */
4938 fits = fits_capacity(util, capacity);
4939
4940 if (!uclamp_is_used())
4941 return fits;
4942
4943 /*
4944 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4945 * uclamp_max. We only care about capacity pressure (by using
4946 * capacity_of()) for comparing against the real util.
4947 *
4948 * If a task is boosted to 1024 for example, we don't want a tiny
4949 * pressure to skew the check whether it fits a CPU or not.
4950 *
4951 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4952 * should fit a little cpu even if there's some pressure.
4953 *
4954 * Only exception is for HW or cpufreq pressure since it has a direct impact
4955 * on available OPP of the system.
4956 *
4957 * We honour it for uclamp_min only as a drop in performance level
4958 * could result in not getting the requested minimum performance level.
4959 *
4960 * For uclamp_max, we can tolerate a drop in performance level as the
4961 * goal is to cap the task. So it's okay if it's getting less.
4962 */
4963 capacity_orig = arch_scale_cpu_capacity(cpu);
4964
4965 /*
4966 * We want to force a task to fit a cpu as implied by uclamp_max.
4967 * But we do have some corner cases to cater for..
4968 *
4969 *
4970 * C=z
4971 * | ___
4972 * | C=y | |
4973 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4974 * | C=x | | | |
4975 * | ___ | | | |
4976 * | | | | | | | (util somewhere in this region)
4977 * | | | | | | |
4978 * | | | | | | |
4979 * +----------------------------------------
4980 * CPU0 CPU1 CPU2
4981 *
4982 * In the above example if a task is capped to a specific performance
4983 * point, y, then when:
4984 *
4985 * * util = 80% of x then it does not fit on CPU0 and should migrate
4986 * to CPU1
4987 * * util = 80% of y then it is forced to fit on CPU1 to honour
4988 * uclamp_max request.
4989 *
4990 * which is what we're enforcing here. A task always fits if
4991 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4992 * the normal upmigration rules should withhold still.
4993 *
4994 * Only exception is when we are on max capacity, then we need to be
4995 * careful not to block overutilized state. This is so because:
4996 *
4997 * 1. There's no concept of capping at max_capacity! We can't go
4998 * beyond this performance level anyway.
4999 * 2. The system is being saturated when we're operating near
5000 * max capacity, it doesn't make sense to block overutilized.
5001 */
5002 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5003 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5004 fits = fits || uclamp_max_fits;
5005
5006 /*
5007 *
5008 * C=z
5009 * | ___ (region a, capped, util >= uclamp_max)
5010 * | C=y | |
5011 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5012 * | C=x | | | |
5013 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
5014 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5015 * | | | | | | |
5016 * | | | | | | | (region c, boosted, util < uclamp_min)
5017 * +----------------------------------------
5018 * CPU0 CPU1 CPU2
5019 *
5020 * a) If util > uclamp_max, then we're capped, we don't care about
5021 * actual fitness value here. We only care if uclamp_max fits
5022 * capacity without taking margin/pressure into account.
5023 * See comment above.
5024 *
5025 * b) If uclamp_min <= util <= uclamp_max, then the normal
5026 * fits_capacity() rules apply. Except we need to ensure that we
5027 * enforce we remain within uclamp_max, see comment above.
5028 *
5029 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5030 * need to take into account the boosted value fits the CPU without
5031 * taking margin/pressure into account.
5032 *
5033 * Cases (a) and (b) are handled in the 'fits' variable already. We
5034 * just need to consider an extra check for case (c) after ensuring we
5035 * handle the case uclamp_min > uclamp_max.
5036 */
5037 uclamp_min = min(uclamp_min, uclamp_max);
5038 if (fits && (util < uclamp_min) &&
5039 (uclamp_min > get_actual_cpu_capacity(cpu)))
5040 return -1;
5041
5042 return fits;
5043 }
5044
task_fits_cpu(struct task_struct * p,int cpu)5045 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5046 {
5047 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5048 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5049 unsigned long util = task_util_est(p);
5050 /*
5051 * Return true only if the cpu fully fits the task requirements, which
5052 * include the utilization but also the performance hints.
5053 */
5054 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5055 }
5056
update_misfit_status(struct task_struct * p,struct rq * rq)5057 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5058 {
5059 int cpu = cpu_of(rq);
5060
5061 if (!sched_asym_cpucap_active())
5062 return;
5063
5064 /*
5065 * Affinity allows us to go somewhere higher? Or are we on biggest
5066 * available CPU already? Or do we fit into this CPU ?
5067 */
5068 if (!p || (p->nr_cpus_allowed == 1) ||
5069 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
5070 task_fits_cpu(p, cpu)) {
5071
5072 rq->misfit_task_load = 0;
5073 return;
5074 }
5075
5076 /*
5077 * Make sure that misfit_task_load will not be null even if
5078 * task_h_load() returns 0.
5079 */
5080 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5081 }
5082
__setparam_fair(struct task_struct * p,const struct sched_attr * attr)5083 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
5084 {
5085 struct sched_entity *se = &p->se;
5086
5087 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5088 if (attr->sched_runtime) {
5089 se->custom_slice = 1;
5090 se->slice = clamp_t(u64, attr->sched_runtime,
5091 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */
5092 NSEC_PER_MSEC*100); /* HZ=100 / 10 */
5093 } else {
5094 se->custom_slice = 0;
5095 se->slice = sysctl_sched_base_slice;
5096 }
5097 }
5098
5099 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5100 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5101 {
5102 u64 vslice, vruntime = avg_vruntime(cfs_rq);
5103 s64 lag = 0;
5104
5105 if (!se->custom_slice)
5106 se->slice = sysctl_sched_base_slice;
5107 vslice = calc_delta_fair(se->slice, se);
5108
5109 /*
5110 * Due to how V is constructed as the weighted average of entities,
5111 * adding tasks with positive lag, or removing tasks with negative lag
5112 * will move 'time' backwards, this can screw around with the lag of
5113 * other tasks.
5114 *
5115 * EEVDF: placement strategy #1 / #2
5116 */
5117 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) {
5118 struct sched_entity *curr = cfs_rq->curr;
5119 unsigned long load;
5120
5121 lag = se->vlag;
5122
5123 /*
5124 * If we want to place a task and preserve lag, we have to
5125 * consider the effect of the new entity on the weighted
5126 * average and compensate for this, otherwise lag can quickly
5127 * evaporate.
5128 *
5129 * Lag is defined as:
5130 *
5131 * lag_i = S - s_i = w_i * (V - v_i)
5132 *
5133 * To avoid the 'w_i' term all over the place, we only track
5134 * the virtual lag:
5135 *
5136 * vl_i = V - v_i <=> v_i = V - vl_i
5137 *
5138 * And we take V to be the weighted average of all v:
5139 *
5140 * V = (\Sum w_j*v_j) / W
5141 *
5142 * Where W is: \Sum w_j
5143 *
5144 * Then, the weighted average after adding an entity with lag
5145 * vl_i is given by:
5146 *
5147 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5148 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5149 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5150 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
5151 * = V - w_i*vl_i / (W + w_i)
5152 *
5153 * And the actual lag after adding an entity with vl_i is:
5154 *
5155 * vl'_i = V' - v_i
5156 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5157 * = vl_i - w_i*vl_i / (W + w_i)
5158 *
5159 * Which is strictly less than vl_i. So in order to preserve lag
5160 * we should inflate the lag before placement such that the
5161 * effective lag after placement comes out right.
5162 *
5163 * As such, invert the above relation for vl'_i to get the vl_i
5164 * we need to use such that the lag after placement is the lag
5165 * we computed before dequeue.
5166 *
5167 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5168 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5169 *
5170 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5171 * = W*vl_i
5172 *
5173 * vl_i = (W + w_i)*vl'_i / W
5174 */
5175 load = cfs_rq->avg_load;
5176 if (curr && curr->on_rq)
5177 load += scale_load_down(curr->load.weight);
5178
5179 lag *= load + scale_load_down(se->load.weight);
5180 if (WARN_ON_ONCE(!load))
5181 load = 1;
5182 lag = div_s64(lag, load);
5183 }
5184
5185 se->vruntime = vruntime - lag;
5186
5187 if (se->rel_deadline) {
5188 se->deadline += se->vruntime;
5189 se->rel_deadline = 0;
5190 return;
5191 }
5192
5193 /*
5194 * When joining the competition; the existing tasks will be,
5195 * on average, halfway through their slice, as such start tasks
5196 * off with half a slice to ease into the competition.
5197 */
5198 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5199 vslice /= 2;
5200
5201 /*
5202 * EEVDF: vd_i = ve_i + r_i/w_i
5203 */
5204 se->deadline = se->vruntime + vslice;
5205 }
5206
5207 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5208 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5209
5210 static void
5211 requeue_delayed_entity(struct sched_entity *se);
5212
5213 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5214 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5215 {
5216 bool curr = cfs_rq->curr == se;
5217
5218 /*
5219 * If we're the current task, we must renormalise before calling
5220 * update_curr().
5221 */
5222 if (curr)
5223 place_entity(cfs_rq, se, flags);
5224
5225 update_curr(cfs_rq);
5226
5227 /*
5228 * When enqueuing a sched_entity, we must:
5229 * - Update loads to have both entity and cfs_rq synced with now.
5230 * - For group_entity, update its runnable_weight to reflect the new
5231 * h_nr_runnable of its group cfs_rq.
5232 * - For group_entity, update its weight to reflect the new share of
5233 * its group cfs_rq
5234 * - Add its new weight to cfs_rq->load.weight
5235 */
5236 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5237 se_update_runnable(se);
5238 /*
5239 * XXX update_load_avg() above will have attached us to the pelt sum;
5240 * but update_cfs_group() here will re-adjust the weight and have to
5241 * undo/redo all that. Seems wasteful.
5242 */
5243 update_cfs_group(se);
5244
5245 /*
5246 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5247 * we can place the entity.
5248 */
5249 if (!curr)
5250 place_entity(cfs_rq, se, flags);
5251
5252 account_entity_enqueue(cfs_rq, se);
5253
5254 /* Entity has migrated, no longer consider this task hot */
5255 if (flags & ENQUEUE_MIGRATED)
5256 se->exec_start = 0;
5257
5258 check_schedstat_required();
5259 update_stats_enqueue_fair(cfs_rq, se, flags);
5260 if (!curr)
5261 __enqueue_entity(cfs_rq, se);
5262 se->on_rq = 1;
5263
5264 if (cfs_rq->nr_queued == 1) {
5265 check_enqueue_throttle(cfs_rq);
5266 list_add_leaf_cfs_rq(cfs_rq);
5267 #ifdef CONFIG_CFS_BANDWIDTH
5268 if (cfs_rq->pelt_clock_throttled) {
5269 struct rq *rq = rq_of(cfs_rq);
5270
5271 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5272 cfs_rq->throttled_clock_pelt;
5273 cfs_rq->pelt_clock_throttled = 0;
5274 }
5275 #endif
5276 }
5277 }
5278
__clear_buddies_next(struct sched_entity * se)5279 static void __clear_buddies_next(struct sched_entity *se)
5280 {
5281 for_each_sched_entity(se) {
5282 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5283 if (cfs_rq->next != se)
5284 break;
5285
5286 cfs_rq->next = NULL;
5287 }
5288 }
5289
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5290 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5291 {
5292 if (cfs_rq->next == se)
5293 __clear_buddies_next(se);
5294 }
5295
5296 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5297
set_delayed(struct sched_entity * se)5298 static void set_delayed(struct sched_entity *se)
5299 {
5300 se->sched_delayed = 1;
5301
5302 /*
5303 * Delayed se of cfs_rq have no tasks queued on them.
5304 * Do not adjust h_nr_runnable since dequeue_entities()
5305 * will account it for blocked tasks.
5306 */
5307 if (!entity_is_task(se))
5308 return;
5309
5310 for_each_sched_entity(se) {
5311 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5312
5313 cfs_rq->h_nr_runnable--;
5314 }
5315 }
5316
clear_delayed(struct sched_entity * se)5317 static void clear_delayed(struct sched_entity *se)
5318 {
5319 se->sched_delayed = 0;
5320
5321 /*
5322 * Delayed se of cfs_rq have no tasks queued on them.
5323 * Do not adjust h_nr_runnable since a dequeue has
5324 * already accounted for it or an enqueue of a task
5325 * below it will account for it in enqueue_task_fair().
5326 */
5327 if (!entity_is_task(se))
5328 return;
5329
5330 for_each_sched_entity(se) {
5331 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5332
5333 cfs_rq->h_nr_runnable++;
5334 }
5335 }
5336
finish_delayed_dequeue_entity(struct sched_entity * se)5337 static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
5338 {
5339 clear_delayed(se);
5340 if (sched_feat(DELAY_ZERO) && se->vlag > 0)
5341 se->vlag = 0;
5342 }
5343
5344 static bool
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5345 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5346 {
5347 bool sleep = flags & DEQUEUE_SLEEP;
5348 int action = UPDATE_TG;
5349
5350 update_curr(cfs_rq);
5351 clear_buddies(cfs_rq, se);
5352
5353 if (flags & DEQUEUE_DELAYED) {
5354 WARN_ON_ONCE(!se->sched_delayed);
5355 } else {
5356 bool delay = sleep;
5357 /*
5358 * DELAY_DEQUEUE relies on spurious wakeups, special task
5359 * states must not suffer spurious wakeups, excempt them.
5360 */
5361 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
5362 delay = false;
5363
5364 WARN_ON_ONCE(delay && se->sched_delayed);
5365
5366 if (sched_feat(DELAY_DEQUEUE) && delay &&
5367 !entity_eligible(cfs_rq, se)) {
5368 update_load_avg(cfs_rq, se, 0);
5369 set_delayed(se);
5370 return false;
5371 }
5372 }
5373
5374 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5375 action |= DO_DETACH;
5376
5377 /*
5378 * When dequeuing a sched_entity, we must:
5379 * - Update loads to have both entity and cfs_rq synced with now.
5380 * - For group_entity, update its runnable_weight to reflect the new
5381 * h_nr_runnable of its group cfs_rq.
5382 * - Subtract its previous weight from cfs_rq->load.weight.
5383 * - For group entity, update its weight to reflect the new share
5384 * of its group cfs_rq.
5385 */
5386 update_load_avg(cfs_rq, se, action);
5387 se_update_runnable(se);
5388
5389 update_stats_dequeue_fair(cfs_rq, se, flags);
5390
5391 update_entity_lag(cfs_rq, se);
5392 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5393 se->deadline -= se->vruntime;
5394 se->rel_deadline = 1;
5395 }
5396
5397 if (se != cfs_rq->curr)
5398 __dequeue_entity(cfs_rq, se);
5399 se->on_rq = 0;
5400 account_entity_dequeue(cfs_rq, se);
5401
5402 /* return excess runtime on last dequeue */
5403 return_cfs_rq_runtime(cfs_rq);
5404
5405 update_cfs_group(se);
5406
5407 if (flags & DEQUEUE_DELAYED)
5408 finish_delayed_dequeue_entity(se);
5409
5410 if (cfs_rq->nr_queued == 0) {
5411 update_idle_cfs_rq_clock_pelt(cfs_rq);
5412 #ifdef CONFIG_CFS_BANDWIDTH
5413 if (throttled_hierarchy(cfs_rq)) {
5414 struct rq *rq = rq_of(cfs_rq);
5415
5416 list_del_leaf_cfs_rq(cfs_rq);
5417 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5418 cfs_rq->pelt_clock_throttled = 1;
5419 }
5420 #endif
5421 }
5422
5423 return true;
5424 }
5425
5426 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5427 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5428 {
5429 clear_buddies(cfs_rq, se);
5430
5431 /* 'current' is not kept within the tree. */
5432 if (se->on_rq) {
5433 /*
5434 * Any task has to be enqueued before it get to execute on
5435 * a CPU. So account for the time it spent waiting on the
5436 * runqueue.
5437 */
5438 update_stats_wait_end_fair(cfs_rq, se);
5439 __dequeue_entity(cfs_rq, se);
5440 update_load_avg(cfs_rq, se, UPDATE_TG);
5441
5442 set_protect_slice(cfs_rq, se);
5443 }
5444
5445 update_stats_curr_start(cfs_rq, se);
5446 WARN_ON_ONCE(cfs_rq->curr);
5447 cfs_rq->curr = se;
5448
5449 /*
5450 * Track our maximum slice length, if the CPU's load is at
5451 * least twice that of our own weight (i.e. don't track it
5452 * when there are only lesser-weight tasks around):
5453 */
5454 if (schedstat_enabled() &&
5455 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5456 struct sched_statistics *stats;
5457
5458 stats = __schedstats_from_se(se);
5459 __schedstat_set(stats->slice_max,
5460 max((u64)stats->slice_max,
5461 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5462 }
5463
5464 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5465 }
5466
5467 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5468
5469 /*
5470 * Pick the next process, keeping these things in mind, in this order:
5471 * 1) keep things fair between processes/task groups
5472 * 2) pick the "next" process, since someone really wants that to run
5473 * 3) pick the "last" process, for cache locality
5474 * 4) do not run the "skip" process, if something else is available
5475 */
5476 static struct sched_entity *
pick_next_entity(struct rq * rq,struct cfs_rq * cfs_rq)5477 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5478 {
5479 struct sched_entity *se;
5480
5481 se = pick_eevdf(cfs_rq);
5482 if (se->sched_delayed) {
5483 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5484 /*
5485 * Must not reference @se again, see __block_task().
5486 */
5487 return NULL;
5488 }
5489 return se;
5490 }
5491
5492 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5493
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5494 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5495 {
5496 /*
5497 * If still on the runqueue then deactivate_task()
5498 * was not called and update_curr() has to be done:
5499 */
5500 if (prev->on_rq)
5501 update_curr(cfs_rq);
5502
5503 /* throttle cfs_rqs exceeding runtime */
5504 check_cfs_rq_runtime(cfs_rq);
5505
5506 if (prev->on_rq) {
5507 update_stats_wait_start_fair(cfs_rq, prev);
5508 /* Put 'current' back into the tree. */
5509 __enqueue_entity(cfs_rq, prev);
5510 /* in !on_rq case, update occurred at dequeue */
5511 update_load_avg(cfs_rq, prev, 0);
5512 }
5513 WARN_ON_ONCE(cfs_rq->curr != prev);
5514 cfs_rq->curr = NULL;
5515 }
5516
5517 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5518 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5519 {
5520 /*
5521 * Update run-time statistics of the 'current'.
5522 */
5523 update_curr(cfs_rq);
5524
5525 /*
5526 * Ensure that runnable average is periodically updated.
5527 */
5528 update_load_avg(cfs_rq, curr, UPDATE_TG);
5529 update_cfs_group(curr);
5530
5531 #ifdef CONFIG_SCHED_HRTICK
5532 /*
5533 * queued ticks are scheduled to match the slice, so don't bother
5534 * validating it and just reschedule.
5535 */
5536 if (queued) {
5537 resched_curr_lazy(rq_of(cfs_rq));
5538 return;
5539 }
5540 #endif
5541 }
5542
5543
5544 /**************************************************
5545 * CFS bandwidth control machinery
5546 */
5547
5548 #ifdef CONFIG_CFS_BANDWIDTH
5549
5550 #ifdef CONFIG_JUMP_LABEL
5551 static struct static_key __cfs_bandwidth_used;
5552
cfs_bandwidth_used(void)5553 static inline bool cfs_bandwidth_used(void)
5554 {
5555 return static_key_false(&__cfs_bandwidth_used);
5556 }
5557
cfs_bandwidth_usage_inc(void)5558 void cfs_bandwidth_usage_inc(void)
5559 {
5560 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5561 }
5562
cfs_bandwidth_usage_dec(void)5563 void cfs_bandwidth_usage_dec(void)
5564 {
5565 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5566 }
5567 #else /* !CONFIG_JUMP_LABEL: */
cfs_bandwidth_used(void)5568 static bool cfs_bandwidth_used(void)
5569 {
5570 return true;
5571 }
5572
cfs_bandwidth_usage_inc(void)5573 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5574 void cfs_bandwidth_usage_dec(void) {}
5575 #endif /* !CONFIG_JUMP_LABEL */
5576
sched_cfs_bandwidth_slice(void)5577 static inline u64 sched_cfs_bandwidth_slice(void)
5578 {
5579 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5580 }
5581
5582 /*
5583 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5584 * directly instead of rq->clock to avoid adding additional synchronization
5585 * around rq->lock.
5586 *
5587 * requires cfs_b->lock
5588 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5589 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5590 {
5591 s64 runtime;
5592
5593 if (unlikely(cfs_b->quota == RUNTIME_INF))
5594 return;
5595
5596 cfs_b->runtime += cfs_b->quota;
5597 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5598 if (runtime > 0) {
5599 cfs_b->burst_time += runtime;
5600 cfs_b->nr_burst++;
5601 }
5602
5603 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5604 cfs_b->runtime_snap = cfs_b->runtime;
5605 }
5606
tg_cfs_bandwidth(struct task_group * tg)5607 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5608 {
5609 return &tg->cfs_bandwidth;
5610 }
5611
5612 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5613 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5614 struct cfs_rq *cfs_rq, u64 target_runtime)
5615 {
5616 u64 min_amount, amount = 0;
5617
5618 lockdep_assert_held(&cfs_b->lock);
5619
5620 /* note: this is a positive sum as runtime_remaining <= 0 */
5621 min_amount = target_runtime - cfs_rq->runtime_remaining;
5622
5623 if (cfs_b->quota == RUNTIME_INF)
5624 amount = min_amount;
5625 else {
5626 start_cfs_bandwidth(cfs_b);
5627
5628 if (cfs_b->runtime > 0) {
5629 amount = min(cfs_b->runtime, min_amount);
5630 cfs_b->runtime -= amount;
5631 cfs_b->idle = 0;
5632 }
5633 }
5634
5635 cfs_rq->runtime_remaining += amount;
5636
5637 return cfs_rq->runtime_remaining > 0;
5638 }
5639
5640 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5641 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5642 {
5643 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5644 int ret;
5645
5646 raw_spin_lock(&cfs_b->lock);
5647 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5648 raw_spin_unlock(&cfs_b->lock);
5649
5650 return ret;
5651 }
5652
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5653 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5654 {
5655 /* dock delta_exec before expiring quota (as it could span periods) */
5656 cfs_rq->runtime_remaining -= delta_exec;
5657
5658 if (likely(cfs_rq->runtime_remaining > 0))
5659 return;
5660
5661 if (cfs_rq->throttled)
5662 return;
5663 /*
5664 * if we're unable to extend our runtime we resched so that the active
5665 * hierarchy can be throttled
5666 */
5667 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5668 resched_curr(rq_of(cfs_rq));
5669 }
5670
5671 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5672 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5673 {
5674 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5675 return;
5676
5677 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5678 }
5679
cfs_rq_throttled(struct cfs_rq * cfs_rq)5680 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5681 {
5682 return cfs_bandwidth_used() && cfs_rq->throttled;
5683 }
5684
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)5685 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
5686 {
5687 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
5688 }
5689
5690 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5691 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5692 {
5693 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5694 }
5695
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)5696 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
5697 {
5698 return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]);
5699 }
5700
task_is_throttled(struct task_struct * p)5701 static inline bool task_is_throttled(struct task_struct *p)
5702 {
5703 return cfs_bandwidth_used() && p->throttled;
5704 }
5705
5706 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
throttle_cfs_rq_work(struct callback_head * work)5707 static void throttle_cfs_rq_work(struct callback_head *work)
5708 {
5709 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
5710 struct sched_entity *se;
5711 struct cfs_rq *cfs_rq;
5712 struct rq *rq;
5713
5714 WARN_ON_ONCE(p != current);
5715 p->sched_throttle_work.next = &p->sched_throttle_work;
5716
5717 /*
5718 * If task is exiting, then there won't be a return to userspace, so we
5719 * don't have to bother with any of this.
5720 */
5721 if ((p->flags & PF_EXITING))
5722 return;
5723
5724 scoped_guard(task_rq_lock, p) {
5725 se = &p->se;
5726 cfs_rq = cfs_rq_of(se);
5727
5728 /* Raced, forget */
5729 if (p->sched_class != &fair_sched_class)
5730 return;
5731
5732 /*
5733 * If not in limbo, then either replenish has happened or this
5734 * task got migrated out of the throttled cfs_rq, move along.
5735 */
5736 if (!cfs_rq->throttle_count)
5737 return;
5738 rq = scope.rq;
5739 update_rq_clock(rq);
5740 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
5741 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
5742 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5743 /*
5744 * Must not set throttled before dequeue or dequeue will
5745 * mistakenly regard this task as an already throttled one.
5746 */
5747 p->throttled = true;
5748 resched_curr(rq);
5749 }
5750 }
5751
init_cfs_throttle_work(struct task_struct * p)5752 void init_cfs_throttle_work(struct task_struct *p)
5753 {
5754 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
5755 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
5756 p->sched_throttle_work.next = &p->sched_throttle_work;
5757 INIT_LIST_HEAD(&p->throttle_node);
5758 }
5759
5760 /*
5761 * Task is throttled and someone wants to dequeue it again:
5762 * it could be sched/core when core needs to do things like
5763 * task affinity change, task group change, task sched class
5764 * change etc. and in these cases, DEQUEUE_SLEEP is not set;
5765 * or the task is blocked after throttled due to freezer etc.
5766 * and in these cases, DEQUEUE_SLEEP is set.
5767 */
5768 static void detach_task_cfs_rq(struct task_struct *p);
dequeue_throttled_task(struct task_struct * p,int flags)5769 static void dequeue_throttled_task(struct task_struct *p, int flags)
5770 {
5771 WARN_ON_ONCE(p->se.on_rq);
5772 list_del_init(&p->throttle_node);
5773
5774 /* task blocked after throttled */
5775 if (flags & DEQUEUE_SLEEP) {
5776 p->throttled = false;
5777 return;
5778 }
5779
5780 /*
5781 * task is migrating off its old cfs_rq, detach
5782 * the task's load from its old cfs_rq.
5783 */
5784 if (task_on_rq_migrating(p))
5785 detach_task_cfs_rq(p);
5786 }
5787
enqueue_throttled_task(struct task_struct * p)5788 static bool enqueue_throttled_task(struct task_struct *p)
5789 {
5790 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
5791
5792 /* @p should have gone through dequeue_throttled_task() first */
5793 WARN_ON_ONCE(!list_empty(&p->throttle_node));
5794
5795 /*
5796 * If the throttled task @p is enqueued to a throttled cfs_rq,
5797 * take the fast path by directly putting the task on the
5798 * target cfs_rq's limbo list.
5799 *
5800 * Do not do that when @p is current because the following race can
5801 * cause @p's group_node to be incorectly re-insterted in its rq's
5802 * cfs_tasks list, despite being throttled:
5803 *
5804 * cpuX cpuY
5805 * p ret2user
5806 * throttle_cfs_rq_work() sched_move_task(p)
5807 * LOCK task_rq_lock
5808 * dequeue_task_fair(p)
5809 * UNLOCK task_rq_lock
5810 * LOCK task_rq_lock
5811 * task_current_donor(p) == true
5812 * task_on_rq_queued(p) == true
5813 * dequeue_task(p)
5814 * put_prev_task(p)
5815 * sched_change_group()
5816 * enqueue_task(p) -> p's new cfs_rq
5817 * is throttled, go
5818 * fast path and skip
5819 * actual enqueue
5820 * set_next_task(p)
5821 * list_move(&se->group_node, &rq->cfs_tasks); // bug
5822 * schedule()
5823 *
5824 * In the above race case, @p current cfs_rq is in the same rq as
5825 * its previous cfs_rq because sched_move_task() only moves a task
5826 * to a different group from the same rq, so we can use its current
5827 * cfs_rq to derive rq and test if the task is current.
5828 */
5829 if (throttled_hierarchy(cfs_rq) &&
5830 !task_current_donor(rq_of(cfs_rq), p)) {
5831 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5832 return true;
5833 }
5834
5835 /* we can't take the fast path, do an actual enqueue*/
5836 p->throttled = false;
5837 return false;
5838 }
5839
5840 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
tg_unthrottle_up(struct task_group * tg,void * data)5841 static int tg_unthrottle_up(struct task_group *tg, void *data)
5842 {
5843 struct rq *rq = data;
5844 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5845 struct task_struct *p, *tmp;
5846
5847 if (--cfs_rq->throttle_count)
5848 return 0;
5849
5850 if (cfs_rq->pelt_clock_throttled) {
5851 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5852 cfs_rq->throttled_clock_pelt;
5853 cfs_rq->pelt_clock_throttled = 0;
5854 }
5855
5856 if (cfs_rq->throttled_clock_self) {
5857 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5858
5859 cfs_rq->throttled_clock_self = 0;
5860
5861 if (WARN_ON_ONCE((s64)delta < 0))
5862 delta = 0;
5863
5864 cfs_rq->throttled_clock_self_time += delta;
5865 }
5866
5867 /* Re-enqueue the tasks that have been throttled at this level. */
5868 list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) {
5869 list_del_init(&p->throttle_node);
5870 p->throttled = false;
5871 enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP);
5872 }
5873
5874 /* Add cfs_rq with load or one or more already running entities to the list */
5875 if (!cfs_rq_is_decayed(cfs_rq))
5876 list_add_leaf_cfs_rq(cfs_rq);
5877
5878 return 0;
5879 }
5880
task_has_throttle_work(struct task_struct * p)5881 static inline bool task_has_throttle_work(struct task_struct *p)
5882 {
5883 return p->sched_throttle_work.next != &p->sched_throttle_work;
5884 }
5885
task_throttle_setup_work(struct task_struct * p)5886 static inline void task_throttle_setup_work(struct task_struct *p)
5887 {
5888 if (task_has_throttle_work(p))
5889 return;
5890
5891 /*
5892 * Kthreads and exiting tasks don't return to userspace, so adding the
5893 * work is pointless
5894 */
5895 if ((p->flags & (PF_EXITING | PF_KTHREAD)))
5896 return;
5897
5898 task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
5899 }
5900
record_throttle_clock(struct cfs_rq * cfs_rq)5901 static void record_throttle_clock(struct cfs_rq *cfs_rq)
5902 {
5903 struct rq *rq = rq_of(cfs_rq);
5904
5905 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5906 cfs_rq->throttled_clock = rq_clock(rq);
5907
5908 if (!cfs_rq->throttled_clock_self)
5909 cfs_rq->throttled_clock_self = rq_clock(rq);
5910 }
5911
tg_throttle_down(struct task_group * tg,void * data)5912 static int tg_throttle_down(struct task_group *tg, void *data)
5913 {
5914 struct rq *rq = data;
5915 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5916
5917 if (cfs_rq->throttle_count++)
5918 return 0;
5919
5920 /*
5921 * For cfs_rqs that still have entities enqueued, PELT clock
5922 * stop happens at dequeue time when all entities are dequeued.
5923 */
5924 if (!cfs_rq->nr_queued) {
5925 list_del_leaf_cfs_rq(cfs_rq);
5926 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5927 cfs_rq->pelt_clock_throttled = 1;
5928 }
5929
5930 WARN_ON_ONCE(cfs_rq->throttled_clock_self);
5931 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
5932 return 0;
5933 }
5934
throttle_cfs_rq(struct cfs_rq * cfs_rq)5935 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5936 {
5937 struct rq *rq = rq_of(cfs_rq);
5938 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5939 int dequeue = 1;
5940
5941 raw_spin_lock(&cfs_b->lock);
5942 /* This will start the period timer if necessary */
5943 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5944 /*
5945 * We have raced with bandwidth becoming available, and if we
5946 * actually throttled the timer might not unthrottle us for an
5947 * entire period. We additionally needed to make sure that any
5948 * subsequent check_cfs_rq_runtime calls agree not to throttle
5949 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5950 * for 1ns of runtime rather than just check cfs_b.
5951 */
5952 dequeue = 0;
5953 } else {
5954 list_add_tail_rcu(&cfs_rq->throttled_list,
5955 &cfs_b->throttled_cfs_rq);
5956 }
5957 raw_spin_unlock(&cfs_b->lock);
5958
5959 if (!dequeue)
5960 return false; /* Throttle no longer required. */
5961
5962 /* freeze hierarchy runnable averages while throttled */
5963 rcu_read_lock();
5964 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5965 rcu_read_unlock();
5966
5967 /*
5968 * Note: distribution will already see us throttled via the
5969 * throttled-list. rq->lock protects completion.
5970 */
5971 cfs_rq->throttled = 1;
5972 WARN_ON_ONCE(cfs_rq->throttled_clock);
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 = cfs_rq->tg->se[cpu_of(rq)];
5981
5982 /*
5983 * It's possible we are called with runtime_remaining < 0 due to things
5984 * like async unthrottled us with a positive runtime_remaining but other
5985 * still running entities consumed those runtime before we reached here.
5986 *
5987 * We can't unthrottle this cfs_rq without any runtime remaining because
5988 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
5989 * which is not supposed to happen on unthrottle path.
5990 */
5991 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
5992 return;
5993
5994 cfs_rq->throttled = 0;
5995
5996 update_rq_clock(rq);
5997
5998 raw_spin_lock(&cfs_b->lock);
5999 if (cfs_rq->throttled_clock) {
6000 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
6001 cfs_rq->throttled_clock = 0;
6002 }
6003 list_del_rcu(&cfs_rq->throttled_list);
6004 raw_spin_unlock(&cfs_b->lock);
6005
6006 /* update hierarchical throttle state */
6007 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6008
6009 if (!cfs_rq->load.weight) {
6010 if (!cfs_rq->on_list)
6011 return;
6012 /*
6013 * Nothing to run but something to decay (on_list)?
6014 * Complete the branch.
6015 */
6016 for_each_sched_entity(se) {
6017 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6018 break;
6019 }
6020 }
6021
6022 assert_list_leaf_cfs_rq(rq);
6023
6024 /* Determine whether we need to wake up potentially idle CPU: */
6025 if (rq->curr == rq->idle && rq->cfs.nr_queued)
6026 resched_curr(rq);
6027 }
6028
__cfsb_csd_unthrottle(void * arg)6029 static void __cfsb_csd_unthrottle(void *arg)
6030 {
6031 struct cfs_rq *cursor, *tmp;
6032 struct rq *rq = arg;
6033 struct rq_flags rf;
6034
6035 rq_lock(rq, &rf);
6036
6037 /*
6038 * Iterating over the list can trigger several call to
6039 * update_rq_clock() in unthrottle_cfs_rq().
6040 * Do it once and skip the potential next ones.
6041 */
6042 update_rq_clock(rq);
6043 rq_clock_start_loop_update(rq);
6044
6045 /*
6046 * Since we hold rq lock we're safe from concurrent manipulation of
6047 * the CSD list. However, this RCU critical section annotates the
6048 * fact that we pair with sched_free_group_rcu(), so that we cannot
6049 * race with group being freed in the window between removing it
6050 * from the list and advancing to the next entry in the list.
6051 */
6052 rcu_read_lock();
6053
6054 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6055 throttled_csd_list) {
6056 list_del_init(&cursor->throttled_csd_list);
6057
6058 if (cfs_rq_throttled(cursor))
6059 unthrottle_cfs_rq(cursor);
6060 }
6061
6062 rcu_read_unlock();
6063
6064 rq_clock_stop_loop_update(rq);
6065 rq_unlock(rq, &rf);
6066 }
6067
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6068 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6069 {
6070 struct rq *rq = rq_of(cfs_rq);
6071 bool first;
6072
6073 if (rq == this_rq()) {
6074 unthrottle_cfs_rq(cfs_rq);
6075 return;
6076 }
6077
6078 /* Already enqueued */
6079 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
6080 return;
6081
6082 first = list_empty(&rq->cfsb_csd_list);
6083 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6084 if (first)
6085 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6086 }
6087
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6088 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6089 {
6090 lockdep_assert_rq_held(rq_of(cfs_rq));
6091
6092 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
6093 cfs_rq->runtime_remaining <= 0))
6094 return;
6095
6096 __unthrottle_cfs_rq_async(cfs_rq);
6097 }
6098
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6099 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6100 {
6101 int this_cpu = smp_processor_id();
6102 u64 runtime, remaining = 1;
6103 bool throttled = false;
6104 struct cfs_rq *cfs_rq, *tmp;
6105 struct rq_flags rf;
6106 struct rq *rq;
6107 LIST_HEAD(local_unthrottle);
6108
6109 rcu_read_lock();
6110 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6111 throttled_list) {
6112 rq = rq_of(cfs_rq);
6113
6114 if (!remaining) {
6115 throttled = true;
6116 break;
6117 }
6118
6119 rq_lock_irqsave(rq, &rf);
6120 if (!cfs_rq_throttled(cfs_rq))
6121 goto next;
6122
6123 /* Already queued for async unthrottle */
6124 if (!list_empty(&cfs_rq->throttled_csd_list))
6125 goto next;
6126
6127 /* By the above checks, this should never be true */
6128 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
6129
6130 raw_spin_lock(&cfs_b->lock);
6131 runtime = -cfs_rq->runtime_remaining + 1;
6132 if (runtime > cfs_b->runtime)
6133 runtime = cfs_b->runtime;
6134 cfs_b->runtime -= runtime;
6135 remaining = cfs_b->runtime;
6136 raw_spin_unlock(&cfs_b->lock);
6137
6138 cfs_rq->runtime_remaining += runtime;
6139
6140 /* we check whether we're throttled above */
6141 if (cfs_rq->runtime_remaining > 0) {
6142 if (cpu_of(rq) != this_cpu) {
6143 unthrottle_cfs_rq_async(cfs_rq);
6144 } else {
6145 /*
6146 * We currently only expect to be unthrottling
6147 * a single cfs_rq locally.
6148 */
6149 WARN_ON_ONCE(!list_empty(&local_unthrottle));
6150 list_add_tail(&cfs_rq->throttled_csd_list,
6151 &local_unthrottle);
6152 }
6153 } else {
6154 throttled = true;
6155 }
6156
6157 next:
6158 rq_unlock_irqrestore(rq, &rf);
6159 }
6160
6161 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6162 throttled_csd_list) {
6163 struct rq *rq = rq_of(cfs_rq);
6164
6165 rq_lock_irqsave(rq, &rf);
6166
6167 list_del_init(&cfs_rq->throttled_csd_list);
6168
6169 if (cfs_rq_throttled(cfs_rq))
6170 unthrottle_cfs_rq(cfs_rq);
6171
6172 rq_unlock_irqrestore(rq, &rf);
6173 }
6174 WARN_ON_ONCE(!list_empty(&local_unthrottle));
6175
6176 rcu_read_unlock();
6177
6178 return throttled;
6179 }
6180
6181 /*
6182 * Responsible for refilling a task_group's bandwidth and unthrottling its
6183 * cfs_rqs as appropriate. If there has been no activity within the last
6184 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6185 * used to track this state.
6186 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6187 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6188 {
6189 int throttled;
6190
6191 /* no need to continue the timer with no bandwidth constraint */
6192 if (cfs_b->quota == RUNTIME_INF)
6193 goto out_deactivate;
6194
6195 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6196 cfs_b->nr_periods += overrun;
6197
6198 /* Refill extra burst quota even if cfs_b->idle */
6199 __refill_cfs_bandwidth_runtime(cfs_b);
6200
6201 /*
6202 * idle depends on !throttled (for the case of a large deficit), and if
6203 * we're going inactive then everything else can be deferred
6204 */
6205 if (cfs_b->idle && !throttled)
6206 goto out_deactivate;
6207
6208 if (!throttled) {
6209 /* mark as potentially idle for the upcoming period */
6210 cfs_b->idle = 1;
6211 return 0;
6212 }
6213
6214 /* account preceding periods in which throttling occurred */
6215 cfs_b->nr_throttled += overrun;
6216
6217 /*
6218 * This check is repeated as we release cfs_b->lock while we unthrottle.
6219 */
6220 while (throttled && cfs_b->runtime > 0) {
6221 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6222 /* we can't nest cfs_b->lock while distributing bandwidth */
6223 throttled = distribute_cfs_runtime(cfs_b);
6224 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6225 }
6226
6227 /*
6228 * While we are ensured activity in the period following an
6229 * unthrottle, this also covers the case in which the new bandwidth is
6230 * insufficient to cover the existing bandwidth deficit. (Forcing the
6231 * timer to remain active while there are any throttled entities.)
6232 */
6233 cfs_b->idle = 0;
6234
6235 return 0;
6236
6237 out_deactivate:
6238 return 1;
6239 }
6240
6241 /* a cfs_rq won't donate quota below this amount */
6242 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6243 /* minimum remaining period time to redistribute slack quota */
6244 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6245 /* how long we wait to gather additional slack before distributing */
6246 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6247
6248 /*
6249 * Are we near the end of the current quota period?
6250 *
6251 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6252 * hrtimer base being cleared by hrtimer_start. In the case of
6253 * migrate_hrtimers, base is never cleared, so we are fine.
6254 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6255 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6256 {
6257 struct hrtimer *refresh_timer = &cfs_b->period_timer;
6258 s64 remaining;
6259
6260 /* if the call-back is running a quota refresh is already occurring */
6261 if (hrtimer_callback_running(refresh_timer))
6262 return 1;
6263
6264 /* is a quota refresh about to occur? */
6265 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6266 if (remaining < (s64)min_expire)
6267 return 1;
6268
6269 return 0;
6270 }
6271
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6272 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6273 {
6274 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6275
6276 /* if there's a quota refresh soon don't bother with slack */
6277 if (runtime_refresh_within(cfs_b, min_left))
6278 return;
6279
6280 /* don't push forwards an existing deferred unthrottle */
6281 if (cfs_b->slack_started)
6282 return;
6283 cfs_b->slack_started = true;
6284
6285 hrtimer_start(&cfs_b->slack_timer,
6286 ns_to_ktime(cfs_bandwidth_slack_period),
6287 HRTIMER_MODE_REL);
6288 }
6289
6290 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6291 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6292 {
6293 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6294 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6295
6296 if (slack_runtime <= 0)
6297 return;
6298
6299 raw_spin_lock(&cfs_b->lock);
6300 if (cfs_b->quota != RUNTIME_INF) {
6301 cfs_b->runtime += slack_runtime;
6302
6303 /* we are under rq->lock, defer unthrottling using a timer */
6304 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6305 !list_empty(&cfs_b->throttled_cfs_rq))
6306 start_cfs_slack_bandwidth(cfs_b);
6307 }
6308 raw_spin_unlock(&cfs_b->lock);
6309
6310 /* even if it's not valid for return we don't want to try again */
6311 cfs_rq->runtime_remaining -= slack_runtime;
6312 }
6313
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6314 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6315 {
6316 if (!cfs_bandwidth_used())
6317 return;
6318
6319 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
6320 return;
6321
6322 __return_cfs_rq_runtime(cfs_rq);
6323 }
6324
6325 /*
6326 * This is done with a timer (instead of inline with bandwidth return) since
6327 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6328 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6329 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6330 {
6331 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6332 unsigned long flags;
6333
6334 /* confirm we're still not at a refresh boundary */
6335 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6336 cfs_b->slack_started = false;
6337
6338 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6339 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6340 return;
6341 }
6342
6343 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6344 runtime = cfs_b->runtime;
6345
6346 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6347
6348 if (!runtime)
6349 return;
6350
6351 distribute_cfs_runtime(cfs_b);
6352 }
6353
6354 /*
6355 * When a group wakes up we want to make sure that its quota is not already
6356 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6357 * runtime as update_curr() throttling can not trigger until it's on-rq.
6358 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6359 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6360 {
6361 if (!cfs_bandwidth_used())
6362 return;
6363
6364 /* an active group must be handled by the update_curr()->put() path */
6365 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6366 return;
6367
6368 /* ensure the group is not already throttled */
6369 if (cfs_rq_throttled(cfs_rq))
6370 return;
6371
6372 /* update runtime allocation */
6373 account_cfs_rq_runtime(cfs_rq, 0);
6374 if (cfs_rq->runtime_remaining <= 0)
6375 throttle_cfs_rq(cfs_rq);
6376 }
6377
sync_throttle(struct task_group * tg,int cpu)6378 static void sync_throttle(struct task_group *tg, int cpu)
6379 {
6380 struct cfs_rq *pcfs_rq, *cfs_rq;
6381
6382 if (!cfs_bandwidth_used())
6383 return;
6384
6385 if (!tg->parent)
6386 return;
6387
6388 cfs_rq = tg->cfs_rq[cpu];
6389 pcfs_rq = tg->parent->cfs_rq[cpu];
6390
6391 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6392 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6393
6394 /*
6395 * It is not enough to sync the "pelt_clock_throttled" indicator
6396 * with the parent cfs_rq when the hierarchy is not queued.
6397 * Always join a throttled hierarchy with PELT clock throttled
6398 * and leaf it to the first enqueue, or distribution to
6399 * unthrottle the PELT clock.
6400 */
6401 if (cfs_rq->throttle_count)
6402 cfs_rq->pelt_clock_throttled = 1;
6403 }
6404
6405 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6406 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6407 {
6408 if (!cfs_bandwidth_used())
6409 return false;
6410
6411 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6412 return false;
6413
6414 /*
6415 * it's possible for a throttled entity to be forced into a running
6416 * state (e.g. set_curr_task), in this case we're finished.
6417 */
6418 if (cfs_rq_throttled(cfs_rq))
6419 return true;
6420
6421 return throttle_cfs_rq(cfs_rq);
6422 }
6423
sched_cfs_slack_timer(struct hrtimer * timer)6424 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6425 {
6426 struct cfs_bandwidth *cfs_b =
6427 container_of(timer, struct cfs_bandwidth, slack_timer);
6428
6429 do_sched_cfs_slack_timer(cfs_b);
6430
6431 return HRTIMER_NORESTART;
6432 }
6433
sched_cfs_period_timer(struct hrtimer * timer)6434 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6435 {
6436 struct cfs_bandwidth *cfs_b =
6437 container_of(timer, struct cfs_bandwidth, period_timer);
6438 unsigned long flags;
6439 int overrun;
6440 int idle = 0;
6441 int count = 0;
6442
6443 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6444 for (;;) {
6445 overrun = hrtimer_forward_now(timer, cfs_b->period);
6446 if (!overrun)
6447 break;
6448
6449 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6450
6451 if (++count > 3) {
6452 u64 new, old = ktime_to_ns(cfs_b->period);
6453
6454 /*
6455 * Grow period by a factor of 2 to avoid losing precision.
6456 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6457 * to fail.
6458 */
6459 new = old * 2;
6460 if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
6461 cfs_b->period = ns_to_ktime(new);
6462 cfs_b->quota *= 2;
6463 cfs_b->burst *= 2;
6464
6465 pr_warn_ratelimited(
6466 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6467 smp_processor_id(),
6468 div_u64(new, NSEC_PER_USEC),
6469 div_u64(cfs_b->quota, NSEC_PER_USEC));
6470 } else {
6471 pr_warn_ratelimited(
6472 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6473 smp_processor_id(),
6474 div_u64(old, NSEC_PER_USEC),
6475 div_u64(cfs_b->quota, NSEC_PER_USEC));
6476 }
6477
6478 /* reset count so we don't come right back in here */
6479 count = 0;
6480 }
6481 }
6482 if (idle)
6483 cfs_b->period_active = 0;
6484 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6485
6486 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6487 }
6488
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6489 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6490 {
6491 raw_spin_lock_init(&cfs_b->lock);
6492 cfs_b->runtime = 0;
6493 cfs_b->quota = RUNTIME_INF;
6494 cfs_b->period = us_to_ktime(default_bw_period_us());
6495 cfs_b->burst = 0;
6496 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6497
6498 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6499 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
6500 HRTIMER_MODE_ABS_PINNED);
6501
6502 /* Add a random offset so that timers interleave */
6503 hrtimer_set_expires(&cfs_b->period_timer,
6504 get_random_u32_below(cfs_b->period));
6505 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
6506 HRTIMER_MODE_REL);
6507 cfs_b->slack_started = false;
6508 }
6509
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6510 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6511 {
6512 cfs_rq->runtime_enabled = 0;
6513 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6514 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6515 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
6516 }
6517
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6518 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6519 {
6520 lockdep_assert_held(&cfs_b->lock);
6521
6522 if (cfs_b->period_active)
6523 return;
6524
6525 cfs_b->period_active = 1;
6526 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6527 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6528 }
6529
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6530 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6531 {
6532 int __maybe_unused i;
6533
6534 /* init_cfs_bandwidth() was not called */
6535 if (!cfs_b->throttled_cfs_rq.next)
6536 return;
6537
6538 hrtimer_cancel(&cfs_b->period_timer);
6539 hrtimer_cancel(&cfs_b->slack_timer);
6540
6541 /*
6542 * It is possible that we still have some cfs_rq's pending on a CSD
6543 * list, though this race is very rare. In order for this to occur, we
6544 * must have raced with the last task leaving the group while there
6545 * exist throttled cfs_rq(s), and the period_timer must have queued the
6546 * CSD item but the remote cpu has not yet processed it. To handle this,
6547 * we can simply flush all pending CSD work inline here. We're
6548 * guaranteed at this point that no additional cfs_rq of this group can
6549 * join a CSD list.
6550 */
6551 for_each_possible_cpu(i) {
6552 struct rq *rq = cpu_rq(i);
6553 unsigned long flags;
6554
6555 if (list_empty(&rq->cfsb_csd_list))
6556 continue;
6557
6558 local_irq_save(flags);
6559 __cfsb_csd_unthrottle(rq);
6560 local_irq_restore(flags);
6561 }
6562 }
6563
6564 /*
6565 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6566 *
6567 * The race is harmless, since modifying bandwidth settings of unhooked group
6568 * bits doesn't do much.
6569 */
6570
6571 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6572 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6573 {
6574 struct task_group *tg;
6575
6576 lockdep_assert_rq_held(rq);
6577
6578 rcu_read_lock();
6579 list_for_each_entry_rcu(tg, &task_groups, list) {
6580 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6581 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6582
6583 raw_spin_lock(&cfs_b->lock);
6584 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6585 raw_spin_unlock(&cfs_b->lock);
6586 }
6587 rcu_read_unlock();
6588 }
6589
6590 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6591 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6592 {
6593 struct task_group *tg;
6594
6595 lockdep_assert_rq_held(rq);
6596
6597 // Do not unthrottle for an active CPU
6598 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
6599 return;
6600
6601 /*
6602 * The rq clock has already been updated in the
6603 * set_rq_offline(), so we should skip updating
6604 * the rq clock again in unthrottle_cfs_rq().
6605 */
6606 rq_clock_start_loop_update(rq);
6607
6608 rcu_read_lock();
6609 list_for_each_entry_rcu(tg, &task_groups, list) {
6610 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6611
6612 if (!cfs_rq->runtime_enabled)
6613 continue;
6614
6615 /*
6616 * Offline rq is schedulable till CPU is completely disabled
6617 * in take_cpu_down(), so we prevent new cfs throttling here.
6618 */
6619 cfs_rq->runtime_enabled = 0;
6620
6621 if (!cfs_rq_throttled(cfs_rq))
6622 continue;
6623
6624 /*
6625 * clock_task is not advancing so we just need to make sure
6626 * there's some valid quota amount
6627 */
6628 cfs_rq->runtime_remaining = 1;
6629 unthrottle_cfs_rq(cfs_rq);
6630 }
6631 rcu_read_unlock();
6632
6633 rq_clock_stop_loop_update(rq);
6634 }
6635
cfs_task_bw_constrained(struct task_struct * p)6636 bool cfs_task_bw_constrained(struct task_struct *p)
6637 {
6638 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6639
6640 if (!cfs_bandwidth_used())
6641 return false;
6642
6643 if (cfs_rq->runtime_enabled ||
6644 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6645 return true;
6646
6647 return false;
6648 }
6649
6650 #ifdef CONFIG_NO_HZ_FULL
6651 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6652 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6653 {
6654 int cpu = cpu_of(rq);
6655
6656 if (!cfs_bandwidth_used())
6657 return;
6658
6659 if (!tick_nohz_full_cpu(cpu))
6660 return;
6661
6662 if (rq->nr_running != 1)
6663 return;
6664
6665 /*
6666 * We know there is only one task runnable and we've just picked it. The
6667 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6668 * be otherwise able to stop the tick. Just need to check if we are using
6669 * bandwidth control.
6670 */
6671 if (cfs_task_bw_constrained(p))
6672 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6673 }
6674 #endif /* CONFIG_NO_HZ_FULL */
6675
6676 #else /* !CONFIG_CFS_BANDWIDTH: */
6677
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6678 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6679 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6680 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6681 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6682 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
task_throttle_setup_work(struct task_struct * p)6683 static void task_throttle_setup_work(struct task_struct *p) {}
task_is_throttled(struct task_struct * p)6684 static bool task_is_throttled(struct task_struct *p) { return false; }
dequeue_throttled_task(struct task_struct * p,int flags)6685 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
enqueue_throttled_task(struct task_struct * p)6686 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
record_throttle_clock(struct cfs_rq * cfs_rq)6687 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
6688
cfs_rq_throttled(struct cfs_rq * cfs_rq)6689 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6690 {
6691 return 0;
6692 }
6693
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)6694 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6695 {
6696 return false;
6697 }
6698
throttled_hierarchy(struct cfs_rq * cfs_rq)6699 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6700 {
6701 return 0;
6702 }
6703
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)6704 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6705 {
6706 return 0;
6707 }
6708
6709 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6710 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6711 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6712 #endif
6713
tg_cfs_bandwidth(struct task_group * tg)6714 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6715 {
6716 return NULL;
6717 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6718 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6719 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6720 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6721 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6722 bool cfs_task_bw_constrained(struct task_struct *p)
6723 {
6724 return false;
6725 }
6726 #endif
6727 #endif /* !CONFIG_CFS_BANDWIDTH */
6728
6729 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6730 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6731 #endif
6732
6733 /**************************************************
6734 * CFS operations on tasks:
6735 */
6736
6737 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6738 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6739 {
6740 struct sched_entity *se = &p->se;
6741
6742 WARN_ON_ONCE(task_rq(p) != rq);
6743
6744 if (rq->cfs.h_nr_queued > 1) {
6745 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6746 u64 slice = se->slice;
6747 s64 delta = slice - ran;
6748
6749 if (delta < 0) {
6750 if (task_current_donor(rq, p))
6751 resched_curr(rq);
6752 return;
6753 }
6754 hrtick_start(rq, delta);
6755 }
6756 }
6757
6758 /*
6759 * called from enqueue/dequeue and updates the hrtick when the
6760 * current task is from our class and nr_running is low enough
6761 * to matter.
6762 */
hrtick_update(struct rq * rq)6763 static void hrtick_update(struct rq *rq)
6764 {
6765 struct task_struct *donor = rq->donor;
6766
6767 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
6768 return;
6769
6770 hrtick_start_fair(rq, donor);
6771 }
6772 #else /* !CONFIG_SCHED_HRTICK: */
6773 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)6774 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6775 {
6776 }
6777
hrtick_update(struct rq * rq)6778 static inline void hrtick_update(struct rq *rq)
6779 {
6780 }
6781 #endif /* !CONFIG_SCHED_HRTICK */
6782
cpu_overutilized(int cpu)6783 static inline bool cpu_overutilized(int cpu)
6784 {
6785 unsigned long rq_util_min, rq_util_max;
6786
6787 if (!sched_energy_enabled())
6788 return false;
6789
6790 rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6791 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6792
6793 /* Return true only if the utilization doesn't fit CPU's capacity */
6794 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6795 }
6796
6797 /*
6798 * overutilized value make sense only if EAS is enabled
6799 */
is_rd_overutilized(struct root_domain * rd)6800 static inline bool is_rd_overutilized(struct root_domain *rd)
6801 {
6802 return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
6803 }
6804
set_rd_overutilized(struct root_domain * rd,bool flag)6805 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
6806 {
6807 if (!sched_energy_enabled())
6808 return;
6809
6810 WRITE_ONCE(rd->overutilized, flag);
6811 trace_sched_overutilized_tp(rd, flag);
6812 }
6813
check_update_overutilized_status(struct rq * rq)6814 static inline void check_update_overutilized_status(struct rq *rq)
6815 {
6816 /*
6817 * overutilized field is used for load balancing decisions only
6818 * if energy aware scheduler is being used
6819 */
6820
6821 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
6822 set_rd_overutilized(rq->rd, 1);
6823 }
6824
6825 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)6826 static int sched_idle_rq(struct rq *rq)
6827 {
6828 return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
6829 rq->nr_running);
6830 }
6831
sched_idle_cpu(int cpu)6832 static int sched_idle_cpu(int cpu)
6833 {
6834 return sched_idle_rq(cpu_rq(cpu));
6835 }
6836
6837 static void
requeue_delayed_entity(struct sched_entity * se)6838 requeue_delayed_entity(struct sched_entity *se)
6839 {
6840 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6841
6842 /*
6843 * se->sched_delayed should imply: se->on_rq == 1.
6844 * Because a delayed entity is one that is still on
6845 * the runqueue competing until elegibility.
6846 */
6847 WARN_ON_ONCE(!se->sched_delayed);
6848 WARN_ON_ONCE(!se->on_rq);
6849
6850 if (sched_feat(DELAY_ZERO)) {
6851 update_entity_lag(cfs_rq, se);
6852 if (se->vlag > 0) {
6853 cfs_rq->nr_queued--;
6854 if (se != cfs_rq->curr)
6855 __dequeue_entity(cfs_rq, se);
6856 se->vlag = 0;
6857 place_entity(cfs_rq, se, 0);
6858 if (se != cfs_rq->curr)
6859 __enqueue_entity(cfs_rq, se);
6860 cfs_rq->nr_queued++;
6861 }
6862 }
6863
6864 update_load_avg(cfs_rq, se, 0);
6865 clear_delayed(se);
6866 }
6867
6868 /*
6869 * The enqueue_task method is called before nr_running is
6870 * increased. Here we update the fair scheduling stats and
6871 * then put the task into the rbtree:
6872 */
6873 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)6874 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6875 {
6876 struct cfs_rq *cfs_rq;
6877 struct sched_entity *se = &p->se;
6878 int h_nr_idle = task_has_idle_policy(p);
6879 int h_nr_runnable = 1;
6880 int task_new = !(flags & ENQUEUE_WAKEUP);
6881 int rq_h_nr_queued = rq->cfs.h_nr_queued;
6882 u64 slice = 0;
6883
6884 if (task_is_throttled(p) && enqueue_throttled_task(p))
6885 return;
6886
6887 /*
6888 * The code below (indirectly) updates schedutil which looks at
6889 * the cfs_rq utilization to select a frequency.
6890 * Let's add the task's estimated utilization to the cfs_rq's
6891 * estimated utilization, before we update schedutil.
6892 */
6893 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
6894 util_est_enqueue(&rq->cfs, p);
6895
6896 if (flags & ENQUEUE_DELAYED) {
6897 requeue_delayed_entity(se);
6898 return;
6899 }
6900
6901 /*
6902 * If in_iowait is set, the code below may not trigger any cpufreq
6903 * utilization updates, so do it here explicitly with the IOWAIT flag
6904 * passed.
6905 */
6906 if (p->in_iowait)
6907 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6908
6909 if (task_new && se->sched_delayed)
6910 h_nr_runnable = 0;
6911
6912 for_each_sched_entity(se) {
6913 if (se->on_rq) {
6914 if (se->sched_delayed)
6915 requeue_delayed_entity(se);
6916 break;
6917 }
6918 cfs_rq = cfs_rq_of(se);
6919
6920 /*
6921 * Basically set the slice of group entries to the min_slice of
6922 * their respective cfs_rq. This ensures the group can service
6923 * its entities in the desired time-frame.
6924 */
6925 if (slice) {
6926 se->slice = slice;
6927 se->custom_slice = 1;
6928 }
6929 enqueue_entity(cfs_rq, se, flags);
6930 slice = cfs_rq_min_slice(cfs_rq);
6931
6932 cfs_rq->h_nr_runnable += h_nr_runnable;
6933 cfs_rq->h_nr_queued++;
6934 cfs_rq->h_nr_idle += h_nr_idle;
6935
6936 if (cfs_rq_is_idle(cfs_rq))
6937 h_nr_idle = 1;
6938
6939 flags = ENQUEUE_WAKEUP;
6940 }
6941
6942 for_each_sched_entity(se) {
6943 cfs_rq = cfs_rq_of(se);
6944
6945 update_load_avg(cfs_rq, se, UPDATE_TG);
6946 se_update_runnable(se);
6947 update_cfs_group(se);
6948
6949 se->slice = slice;
6950 if (se != cfs_rq->curr)
6951 min_vruntime_cb_propagate(&se->run_node, NULL);
6952 slice = cfs_rq_min_slice(cfs_rq);
6953
6954 cfs_rq->h_nr_runnable += h_nr_runnable;
6955 cfs_rq->h_nr_queued++;
6956 cfs_rq->h_nr_idle += h_nr_idle;
6957
6958 if (cfs_rq_is_idle(cfs_rq))
6959 h_nr_idle = 1;
6960 }
6961
6962 if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
6963 dl_server_start(&rq->fair_server);
6964
6965 /* At this point se is NULL and we are at root level*/
6966 add_nr_running(rq, 1);
6967
6968 /*
6969 * Since new tasks are assigned an initial util_avg equal to
6970 * half of the spare capacity of their CPU, tiny tasks have the
6971 * ability to cross the overutilized threshold, which will
6972 * result in the load balancer ruining all the task placement
6973 * done by EAS. As a way to mitigate that effect, do not account
6974 * for the first enqueue operation of new tasks during the
6975 * overutilized flag detection.
6976 *
6977 * A better way of solving this problem would be to wait for
6978 * the PELT signals of tasks to converge before taking them
6979 * into account, but that is not straightforward to implement,
6980 * and the following generally works well enough in practice.
6981 */
6982 if (!task_new)
6983 check_update_overutilized_status(rq);
6984
6985 assert_list_leaf_cfs_rq(rq);
6986
6987 hrtick_update(rq);
6988 }
6989
6990 /*
6991 * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
6992 * failing half-way through and resume the dequeue later.
6993 *
6994 * Returns:
6995 * -1 - dequeue delayed
6996 * 0 - dequeue throttled
6997 * 1 - dequeue complete
6998 */
dequeue_entities(struct rq * rq,struct sched_entity * se,int flags)6999 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
7000 {
7001 bool was_sched_idle = sched_idle_rq(rq);
7002 bool task_sleep = flags & DEQUEUE_SLEEP;
7003 bool task_delayed = flags & DEQUEUE_DELAYED;
7004 bool task_throttled = flags & DEQUEUE_THROTTLE;
7005 struct task_struct *p = NULL;
7006 int h_nr_idle = 0;
7007 int h_nr_queued = 0;
7008 int h_nr_runnable = 0;
7009 struct cfs_rq *cfs_rq;
7010 u64 slice = 0;
7011
7012 if (entity_is_task(se)) {
7013 p = task_of(se);
7014 h_nr_queued = 1;
7015 h_nr_idle = task_has_idle_policy(p);
7016 if (task_sleep || task_delayed || !se->sched_delayed)
7017 h_nr_runnable = 1;
7018 }
7019
7020 for_each_sched_entity(se) {
7021 cfs_rq = cfs_rq_of(se);
7022
7023 if (!dequeue_entity(cfs_rq, se, flags)) {
7024 if (p && &p->se == se)
7025 return -1;
7026
7027 slice = cfs_rq_min_slice(cfs_rq);
7028 break;
7029 }
7030
7031 cfs_rq->h_nr_runnable -= h_nr_runnable;
7032 cfs_rq->h_nr_queued -= h_nr_queued;
7033 cfs_rq->h_nr_idle -= h_nr_idle;
7034
7035 if (cfs_rq_is_idle(cfs_rq))
7036 h_nr_idle = h_nr_queued;
7037
7038 if (throttled_hierarchy(cfs_rq) && task_throttled)
7039 record_throttle_clock(cfs_rq);
7040
7041 /* Don't dequeue parent if it has other entities besides us */
7042 if (cfs_rq->load.weight) {
7043 slice = cfs_rq_min_slice(cfs_rq);
7044
7045 /* Avoid re-evaluating load for this entity: */
7046 se = parent_entity(se);
7047 /*
7048 * Bias pick_next to pick a task from this cfs_rq, as
7049 * p is sleeping when it is within its sched_slice.
7050 */
7051 if (task_sleep && se)
7052 set_next_buddy(se);
7053 break;
7054 }
7055 flags |= DEQUEUE_SLEEP;
7056 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7057 }
7058
7059 for_each_sched_entity(se) {
7060 cfs_rq = cfs_rq_of(se);
7061
7062 update_load_avg(cfs_rq, se, UPDATE_TG);
7063 se_update_runnable(se);
7064 update_cfs_group(se);
7065
7066 se->slice = slice;
7067 if (se != cfs_rq->curr)
7068 min_vruntime_cb_propagate(&se->run_node, NULL);
7069 slice = cfs_rq_min_slice(cfs_rq);
7070
7071 cfs_rq->h_nr_runnable -= h_nr_runnable;
7072 cfs_rq->h_nr_queued -= h_nr_queued;
7073 cfs_rq->h_nr_idle -= h_nr_idle;
7074
7075 if (cfs_rq_is_idle(cfs_rq))
7076 h_nr_idle = h_nr_queued;
7077
7078 if (throttled_hierarchy(cfs_rq) && task_throttled)
7079 record_throttle_clock(cfs_rq);
7080 }
7081
7082 sub_nr_running(rq, h_nr_queued);
7083
7084 /* balance early to pull high priority tasks */
7085 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7086 rq->next_balance = jiffies;
7087
7088 if (p && task_delayed) {
7089 WARN_ON_ONCE(!task_sleep);
7090 WARN_ON_ONCE(p->on_rq != 1);
7091
7092 /* Fix-up what dequeue_task_fair() skipped */
7093 hrtick_update(rq);
7094
7095 /*
7096 * Fix-up what block_task() skipped.
7097 *
7098 * Must be last, @p might not be valid after this.
7099 */
7100 __block_task(rq, p);
7101 }
7102
7103 return 1;
7104 }
7105
7106 /*
7107 * The dequeue_task method is called before nr_running is
7108 * decreased. We remove the task from the rbtree and
7109 * update the fair scheduling stats:
7110 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7111 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7112 {
7113 if (task_is_throttled(p)) {
7114 dequeue_throttled_task(p, flags);
7115 return true;
7116 }
7117
7118 if (!p->se.sched_delayed)
7119 util_est_dequeue(&rq->cfs, p);
7120
7121 util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7122 if (dequeue_entities(rq, &p->se, flags) < 0)
7123 return false;
7124
7125 /*
7126 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7127 */
7128
7129 hrtick_update(rq);
7130 return true;
7131 }
7132
cfs_h_nr_delayed(struct rq * rq)7133 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
7134 {
7135 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
7136 }
7137
7138 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7139 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7140 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7141 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7142
7143 #ifdef CONFIG_NO_HZ_COMMON
7144
7145 static struct {
7146 cpumask_var_t idle_cpus_mask;
7147 atomic_t nr_cpus;
7148 int has_blocked; /* Idle CPUS has blocked load */
7149 int needs_update; /* Newly idle CPUs need their next_balance collated */
7150 unsigned long next_balance; /* in jiffy units */
7151 unsigned long next_blocked; /* Next update of blocked load in jiffies */
7152 } nohz ____cacheline_aligned;
7153
7154 #endif /* CONFIG_NO_HZ_COMMON */
7155
cpu_load(struct rq * rq)7156 static unsigned long cpu_load(struct rq *rq)
7157 {
7158 return cfs_rq_load_avg(&rq->cfs);
7159 }
7160
7161 /*
7162 * cpu_load_without - compute CPU load without any contributions from *p
7163 * @cpu: the CPU which load is requested
7164 * @p: the task which load should be discounted
7165 *
7166 * The load of a CPU is defined by the load of tasks currently enqueued on that
7167 * CPU as well as tasks which are currently sleeping after an execution on that
7168 * CPU.
7169 *
7170 * This method returns the load of the specified CPU by discounting the load of
7171 * the specified task, whenever the task is currently contributing to the CPU
7172 * load.
7173 */
cpu_load_without(struct rq * rq,struct task_struct * p)7174 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7175 {
7176 struct cfs_rq *cfs_rq;
7177 unsigned int load;
7178
7179 /* Task has no contribution or is new */
7180 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7181 return cpu_load(rq);
7182
7183 cfs_rq = &rq->cfs;
7184 load = READ_ONCE(cfs_rq->avg.load_avg);
7185
7186 /* Discount task's util from CPU's util */
7187 lsub_positive(&load, task_h_load(p));
7188
7189 return load;
7190 }
7191
cpu_runnable(struct rq * rq)7192 static unsigned long cpu_runnable(struct rq *rq)
7193 {
7194 return cfs_rq_runnable_avg(&rq->cfs);
7195 }
7196
cpu_runnable_without(struct rq * rq,struct task_struct * p)7197 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7198 {
7199 struct cfs_rq *cfs_rq;
7200 unsigned int runnable;
7201
7202 /* Task has no contribution or is new */
7203 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7204 return cpu_runnable(rq);
7205
7206 cfs_rq = &rq->cfs;
7207 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7208
7209 /* Discount task's runnable from CPU's runnable */
7210 lsub_positive(&runnable, p->se.avg.runnable_avg);
7211
7212 return runnable;
7213 }
7214
capacity_of(int cpu)7215 static unsigned long capacity_of(int cpu)
7216 {
7217 return cpu_rq(cpu)->cpu_capacity;
7218 }
7219
record_wakee(struct task_struct * p)7220 static void record_wakee(struct task_struct *p)
7221 {
7222 /*
7223 * Only decay a single time; tasks that have less then 1 wakeup per
7224 * jiffy will not have built up many flips.
7225 */
7226 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7227 current->wakee_flips >>= 1;
7228 current->wakee_flip_decay_ts = jiffies;
7229 }
7230
7231 if (current->last_wakee != p) {
7232 current->last_wakee = p;
7233 current->wakee_flips++;
7234 }
7235 }
7236
7237 /*
7238 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7239 *
7240 * A waker of many should wake a different task than the one last awakened
7241 * at a frequency roughly N times higher than one of its wakees.
7242 *
7243 * In order to determine whether we should let the load spread vs consolidating
7244 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7245 * partner, and a factor of lls_size higher frequency in the other.
7246 *
7247 * With both conditions met, we can be relatively sure that the relationship is
7248 * non-monogamous, with partner count exceeding socket size.
7249 *
7250 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7251 * whatever is irrelevant, spread criteria is apparent partner count exceeds
7252 * socket size.
7253 */
wake_wide(struct task_struct * p)7254 static int wake_wide(struct task_struct *p)
7255 {
7256 unsigned int master = current->wakee_flips;
7257 unsigned int slave = p->wakee_flips;
7258 int factor = __this_cpu_read(sd_llc_size);
7259
7260 if (master < slave)
7261 swap(master, slave);
7262 if (slave < factor || master < slave * factor)
7263 return 0;
7264 return 1;
7265 }
7266
7267 /*
7268 * The purpose of wake_affine() is to quickly determine on which CPU we can run
7269 * soonest. For the purpose of speed we only consider the waking and previous
7270 * CPU.
7271 *
7272 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7273 * cache-affine and is (or will be) idle.
7274 *
7275 * wake_affine_weight() - considers the weight to reflect the average
7276 * scheduling latency of the CPUs. This seems to work
7277 * for the overloaded case.
7278 */
7279 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7280 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7281 {
7282 /*
7283 * If this_cpu is idle, it implies the wakeup is from interrupt
7284 * context. Only allow the move if cache is shared. Otherwise an
7285 * interrupt intensive workload could force all tasks onto one
7286 * node depending on the IO topology or IRQ affinity settings.
7287 *
7288 * If the prev_cpu is idle and cache affine then avoid a migration.
7289 * There is no guarantee that the cache hot data from an interrupt
7290 * is more important than cache hot data on the prev_cpu and from
7291 * a cpufreq perspective, it's better to have higher utilisation
7292 * on one CPU.
7293 */
7294 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7295 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7296
7297 if (sync) {
7298 struct rq *rq = cpu_rq(this_cpu);
7299
7300 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
7301 return this_cpu;
7302 }
7303
7304 if (available_idle_cpu(prev_cpu))
7305 return prev_cpu;
7306
7307 return nr_cpumask_bits;
7308 }
7309
7310 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7311 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7312 int this_cpu, int prev_cpu, int sync)
7313 {
7314 s64 this_eff_load, prev_eff_load;
7315 unsigned long task_load;
7316
7317 this_eff_load = cpu_load(cpu_rq(this_cpu));
7318
7319 if (sync) {
7320 unsigned long current_load = task_h_load(current);
7321
7322 if (current_load > this_eff_load)
7323 return this_cpu;
7324
7325 this_eff_load -= current_load;
7326 }
7327
7328 task_load = task_h_load(p);
7329
7330 this_eff_load += task_load;
7331 if (sched_feat(WA_BIAS))
7332 this_eff_load *= 100;
7333 this_eff_load *= capacity_of(prev_cpu);
7334
7335 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7336 prev_eff_load -= task_load;
7337 if (sched_feat(WA_BIAS))
7338 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7339 prev_eff_load *= capacity_of(this_cpu);
7340
7341 /*
7342 * If sync, adjust the weight of prev_eff_load such that if
7343 * prev_eff == this_eff that select_idle_sibling() will consider
7344 * stacking the wakee on top of the waker if no other CPU is
7345 * idle.
7346 */
7347 if (sync)
7348 prev_eff_load += 1;
7349
7350 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7351 }
7352
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7353 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7354 int this_cpu, int prev_cpu, int sync)
7355 {
7356 int target = nr_cpumask_bits;
7357
7358 if (sched_feat(WA_IDLE))
7359 target = wake_affine_idle(this_cpu, prev_cpu, sync);
7360
7361 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7362 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7363
7364 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7365 if (target != this_cpu)
7366 return prev_cpu;
7367
7368 schedstat_inc(sd->ttwu_move_affine);
7369 schedstat_inc(p->stats.nr_wakeups_affine);
7370 return target;
7371 }
7372
7373 static struct sched_group *
7374 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7375
7376 /*
7377 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7378 */
7379 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7380 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7381 {
7382 unsigned long load, min_load = ULONG_MAX;
7383 unsigned int min_exit_latency = UINT_MAX;
7384 u64 latest_idle_timestamp = 0;
7385 int least_loaded_cpu = this_cpu;
7386 int shallowest_idle_cpu = -1;
7387 int i;
7388
7389 /* Check if we have any choice: */
7390 if (group->group_weight == 1)
7391 return cpumask_first(sched_group_span(group));
7392
7393 /* Traverse only the allowed CPUs */
7394 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7395 struct rq *rq = cpu_rq(i);
7396
7397 if (!sched_core_cookie_match(rq, p))
7398 continue;
7399
7400 if (sched_idle_cpu(i))
7401 return i;
7402
7403 if (available_idle_cpu(i)) {
7404 struct cpuidle_state *idle = idle_get_state(rq);
7405 if (idle && idle->exit_latency < min_exit_latency) {
7406 /*
7407 * We give priority to a CPU whose idle state
7408 * has the smallest exit latency irrespective
7409 * of any idle timestamp.
7410 */
7411 min_exit_latency = idle->exit_latency;
7412 latest_idle_timestamp = rq->idle_stamp;
7413 shallowest_idle_cpu = i;
7414 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
7415 rq->idle_stamp > latest_idle_timestamp) {
7416 /*
7417 * If equal or no active idle state, then
7418 * the most recently idled CPU might have
7419 * a warmer cache.
7420 */
7421 latest_idle_timestamp = rq->idle_stamp;
7422 shallowest_idle_cpu = i;
7423 }
7424 } else if (shallowest_idle_cpu == -1) {
7425 load = cpu_load(cpu_rq(i));
7426 if (load < min_load) {
7427 min_load = load;
7428 least_loaded_cpu = i;
7429 }
7430 }
7431 }
7432
7433 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7434 }
7435
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7436 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7437 int cpu, int prev_cpu, int sd_flag)
7438 {
7439 int new_cpu = cpu;
7440
7441 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7442 return prev_cpu;
7443
7444 /*
7445 * We need task's util for cpu_util_without, sync it up to
7446 * prev_cpu's last_update_time.
7447 */
7448 if (!(sd_flag & SD_BALANCE_FORK))
7449 sync_entity_load_avg(&p->se);
7450
7451 while (sd) {
7452 struct sched_group *group;
7453 struct sched_domain *tmp;
7454 int weight;
7455
7456 if (!(sd->flags & sd_flag)) {
7457 sd = sd->child;
7458 continue;
7459 }
7460
7461 group = sched_balance_find_dst_group(sd, p, cpu);
7462 if (!group) {
7463 sd = sd->child;
7464 continue;
7465 }
7466
7467 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7468 if (new_cpu == cpu) {
7469 /* Now try balancing at a lower domain level of 'cpu': */
7470 sd = sd->child;
7471 continue;
7472 }
7473
7474 /* Now try balancing at a lower domain level of 'new_cpu': */
7475 cpu = new_cpu;
7476 weight = sd->span_weight;
7477 sd = NULL;
7478 for_each_domain(cpu, tmp) {
7479 if (weight <= tmp->span_weight)
7480 break;
7481 if (tmp->flags & sd_flag)
7482 sd = tmp;
7483 }
7484 }
7485
7486 return new_cpu;
7487 }
7488
__select_idle_cpu(int cpu,struct task_struct * p)7489 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7490 {
7491 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7492 sched_cpu_cookie_match(cpu_rq(cpu), p))
7493 return cpu;
7494
7495 return -1;
7496 }
7497
7498 #ifdef CONFIG_SCHED_SMT
7499 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7500 EXPORT_SYMBOL_GPL(sched_smt_present);
7501
set_idle_cores(int cpu,int val)7502 static inline void set_idle_cores(int cpu, int val)
7503 {
7504 struct sched_domain_shared *sds;
7505
7506 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7507 if (sds)
7508 WRITE_ONCE(sds->has_idle_cores, val);
7509 }
7510
test_idle_cores(int cpu)7511 static inline bool test_idle_cores(int cpu)
7512 {
7513 struct sched_domain_shared *sds;
7514
7515 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7516 if (sds)
7517 return READ_ONCE(sds->has_idle_cores);
7518
7519 return false;
7520 }
7521
7522 /*
7523 * Scans the local SMT mask to see if the entire core is idle, and records this
7524 * information in sd_llc_shared->has_idle_cores.
7525 *
7526 * Since SMT siblings share all cache levels, inspecting this limited remote
7527 * state should be fairly cheap.
7528 */
__update_idle_core(struct rq * rq)7529 void __update_idle_core(struct rq *rq)
7530 {
7531 int core = cpu_of(rq);
7532 int cpu;
7533
7534 rcu_read_lock();
7535 if (test_idle_cores(core))
7536 goto unlock;
7537
7538 for_each_cpu(cpu, cpu_smt_mask(core)) {
7539 if (cpu == core)
7540 continue;
7541
7542 if (!available_idle_cpu(cpu))
7543 goto unlock;
7544 }
7545
7546 set_idle_cores(core, 1);
7547 unlock:
7548 rcu_read_unlock();
7549 }
7550
7551 /*
7552 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7553 * there are no idle cores left in the system; tracked through
7554 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7555 */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7556 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7557 {
7558 bool idle = true;
7559 int cpu;
7560
7561 for_each_cpu(cpu, cpu_smt_mask(core)) {
7562 if (!available_idle_cpu(cpu)) {
7563 idle = false;
7564 if (*idle_cpu == -1) {
7565 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7566 *idle_cpu = cpu;
7567 break;
7568 }
7569 continue;
7570 }
7571 break;
7572 }
7573 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7574 *idle_cpu = cpu;
7575 }
7576
7577 if (idle)
7578 return core;
7579
7580 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7581 return -1;
7582 }
7583
7584 /*
7585 * Scan the local SMT mask for idle CPUs.
7586 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7587 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7588 {
7589 int cpu;
7590
7591 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7592 if (cpu == target)
7593 continue;
7594 /*
7595 * Check if the CPU is in the LLC scheduling domain of @target.
7596 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7597 */
7598 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7599 continue;
7600 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7601 return cpu;
7602 }
7603
7604 return -1;
7605 }
7606
7607 #else /* !CONFIG_SCHED_SMT: */
7608
set_idle_cores(int cpu,int val)7609 static inline void set_idle_cores(int cpu, int val)
7610 {
7611 }
7612
test_idle_cores(int cpu)7613 static inline bool test_idle_cores(int cpu)
7614 {
7615 return false;
7616 }
7617
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7618 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7619 {
7620 return __select_idle_cpu(core, p);
7621 }
7622
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7623 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7624 {
7625 return -1;
7626 }
7627
7628 #endif /* !CONFIG_SCHED_SMT */
7629
7630 /*
7631 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7632 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7633 * average idle time for this rq (as found in rq->avg_idle).
7634 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7635 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7636 {
7637 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7638 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7639 struct sched_domain_shared *sd_share;
7640
7641 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7642
7643 if (sched_feat(SIS_UTIL)) {
7644 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7645 if (sd_share) {
7646 /* because !--nr is the condition to stop scan */
7647 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7648 /* overloaded LLC is unlikely to have idle cpu/core */
7649 if (nr == 1)
7650 return -1;
7651 }
7652 }
7653
7654 if (static_branch_unlikely(&sched_cluster_active)) {
7655 struct sched_group *sg = sd->groups;
7656
7657 if (sg->flags & SD_CLUSTER) {
7658 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7659 if (!cpumask_test_cpu(cpu, cpus))
7660 continue;
7661
7662 if (has_idle_core) {
7663 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7664 if ((unsigned int)i < nr_cpumask_bits)
7665 return i;
7666 } else {
7667 if (--nr <= 0)
7668 return -1;
7669 idle_cpu = __select_idle_cpu(cpu, p);
7670 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7671 return idle_cpu;
7672 }
7673 }
7674 cpumask_andnot(cpus, cpus, sched_group_span(sg));
7675 }
7676 }
7677
7678 for_each_cpu_wrap(cpu, cpus, target + 1) {
7679 if (has_idle_core) {
7680 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7681 if ((unsigned int)i < nr_cpumask_bits)
7682 return i;
7683
7684 } else {
7685 if (--nr <= 0)
7686 return -1;
7687 idle_cpu = __select_idle_cpu(cpu, p);
7688 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7689 break;
7690 }
7691 }
7692
7693 if (has_idle_core)
7694 set_idle_cores(target, false);
7695
7696 return idle_cpu;
7697 }
7698
7699 /*
7700 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7701 * the task fits. If no CPU is big enough, but there are idle ones, try to
7702 * maximize capacity.
7703 */
7704 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7705 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7706 {
7707 unsigned long task_util, util_min, util_max, best_cap = 0;
7708 int fits, best_fits = 0;
7709 int cpu, best_cpu = -1;
7710 struct cpumask *cpus;
7711
7712 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7713 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7714
7715 task_util = task_util_est(p);
7716 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7717 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7718
7719 for_each_cpu_wrap(cpu, cpus, target) {
7720 unsigned long cpu_cap = capacity_of(cpu);
7721
7722 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7723 continue;
7724
7725 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7726
7727 /* This CPU fits with all requirements */
7728 if (fits > 0)
7729 return cpu;
7730 /*
7731 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7732 * Look for the CPU with best capacity.
7733 */
7734 else if (fits < 0)
7735 cpu_cap = get_actual_cpu_capacity(cpu);
7736
7737 /*
7738 * First, select CPU which fits better (-1 being better than 0).
7739 * Then, select the one with best capacity at same level.
7740 */
7741 if ((fits < best_fits) ||
7742 ((fits == best_fits) && (cpu_cap > best_cap))) {
7743 best_cap = cpu_cap;
7744 best_cpu = cpu;
7745 best_fits = fits;
7746 }
7747 }
7748
7749 return best_cpu;
7750 }
7751
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)7752 static inline bool asym_fits_cpu(unsigned long util,
7753 unsigned long util_min,
7754 unsigned long util_max,
7755 int cpu)
7756 {
7757 if (sched_asym_cpucap_active())
7758 /*
7759 * Return true only if the cpu fully fits the task requirements
7760 * which include the utilization and the performance hints.
7761 */
7762 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7763
7764 return true;
7765 }
7766
7767 /*
7768 * Try and locate an idle core/thread in the LLC cache domain.
7769 */
select_idle_sibling(struct task_struct * p,int prev,int target)7770 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7771 {
7772 bool has_idle_core = false;
7773 struct sched_domain *sd;
7774 unsigned long task_util, util_min, util_max;
7775 int i, recent_used_cpu, prev_aff = -1;
7776
7777 /*
7778 * On asymmetric system, update task utilization because we will check
7779 * that the task fits with CPU's capacity.
7780 */
7781 if (sched_asym_cpucap_active()) {
7782 sync_entity_load_avg(&p->se);
7783 task_util = task_util_est(p);
7784 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7785 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7786 }
7787
7788 /*
7789 * per-cpu select_rq_mask usage
7790 */
7791 lockdep_assert_irqs_disabled();
7792
7793 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7794 asym_fits_cpu(task_util, util_min, util_max, target))
7795 return target;
7796
7797 /*
7798 * If the previous CPU is cache affine and idle, don't be stupid:
7799 */
7800 if (prev != target && cpus_share_cache(prev, target) &&
7801 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7802 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7803
7804 if (!static_branch_unlikely(&sched_cluster_active) ||
7805 cpus_share_resources(prev, target))
7806 return prev;
7807
7808 prev_aff = prev;
7809 }
7810
7811 /*
7812 * Allow a per-cpu kthread to stack with the wakee if the
7813 * kworker thread and the tasks previous CPUs are the same.
7814 * The assumption is that the wakee queued work for the
7815 * per-cpu kthread that is now complete and the wakeup is
7816 * essentially a sync wakeup. An obvious example of this
7817 * pattern is IO completions.
7818 */
7819 if (is_per_cpu_kthread(current) &&
7820 in_task() &&
7821 prev == smp_processor_id() &&
7822 this_rq()->nr_running <= 1 &&
7823 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7824 return prev;
7825 }
7826
7827 /* Check a recently used CPU as a potential idle candidate: */
7828 recent_used_cpu = p->recent_used_cpu;
7829 p->recent_used_cpu = prev;
7830 if (recent_used_cpu != prev &&
7831 recent_used_cpu != target &&
7832 cpus_share_cache(recent_used_cpu, target) &&
7833 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7834 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7835 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7836
7837 if (!static_branch_unlikely(&sched_cluster_active) ||
7838 cpus_share_resources(recent_used_cpu, target))
7839 return recent_used_cpu;
7840
7841 } else {
7842 recent_used_cpu = -1;
7843 }
7844
7845 /*
7846 * For asymmetric CPU capacity systems, our domain of interest is
7847 * sd_asym_cpucapacity rather than sd_llc.
7848 */
7849 if (sched_asym_cpucap_active()) {
7850 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7851 /*
7852 * On an asymmetric CPU capacity system where an exclusive
7853 * cpuset defines a symmetric island (i.e. one unique
7854 * capacity_orig value through the cpuset), the key will be set
7855 * but the CPUs within that cpuset will not have a domain with
7856 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7857 * capacity path.
7858 */
7859 if (sd) {
7860 i = select_idle_capacity(p, sd, target);
7861 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7862 }
7863 }
7864
7865 sd = rcu_dereference(per_cpu(sd_llc, target));
7866 if (!sd)
7867 return target;
7868
7869 if (sched_smt_active()) {
7870 has_idle_core = test_idle_cores(target);
7871
7872 if (!has_idle_core && cpus_share_cache(prev, target)) {
7873 i = select_idle_smt(p, sd, prev);
7874 if ((unsigned int)i < nr_cpumask_bits)
7875 return i;
7876 }
7877 }
7878
7879 i = select_idle_cpu(p, sd, has_idle_core, target);
7880 if ((unsigned)i < nr_cpumask_bits)
7881 return i;
7882
7883 /*
7884 * For cluster machines which have lower sharing cache like L2 or
7885 * LLC Tag, we tend to find an idle CPU in the target's cluster
7886 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
7887 * use them if possible when no idle CPU found in select_idle_cpu().
7888 */
7889 if ((unsigned int)prev_aff < nr_cpumask_bits)
7890 return prev_aff;
7891 if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
7892 return recent_used_cpu;
7893
7894 return target;
7895 }
7896
7897 /**
7898 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7899 * @cpu: the CPU to get the utilization for
7900 * @p: task for which the CPU utilization should be predicted or NULL
7901 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7902 * @boost: 1 to enable boosting, otherwise 0
7903 *
7904 * The unit of the return value must be the same as the one of CPU capacity
7905 * so that CPU utilization can be compared with CPU capacity.
7906 *
7907 * CPU utilization is the sum of running time of runnable tasks plus the
7908 * recent utilization of currently non-runnable tasks on that CPU.
7909 * It represents the amount of CPU capacity currently used by CFS tasks in
7910 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7911 * capacity at f_max.
7912 *
7913 * The estimated CPU utilization is defined as the maximum between CPU
7914 * utilization and sum of the estimated utilization of the currently
7915 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7916 * previously-executed tasks, which helps better deduce how busy a CPU will
7917 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7918 * of such a task would be significantly decayed at this point of time.
7919 *
7920 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7921 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7922 * utilization. Boosting is implemented in cpu_util() so that internal
7923 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7924 * latter via cpu_util_cfs_boost().
7925 *
7926 * CPU utilization can be higher than the current CPU capacity
7927 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7928 * of rounding errors as well as task migrations or wakeups of new tasks.
7929 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7930 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7931 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7932 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7933 * though since this is useful for predicting the CPU capacity required
7934 * after task migrations (scheduler-driven DVFS).
7935 *
7936 * Return: (Boosted) (estimated) utilization for the specified CPU.
7937 */
7938 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)7939 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7940 {
7941 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7942 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7943 unsigned long runnable;
7944
7945 if (boost) {
7946 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7947 util = max(util, runnable);
7948 }
7949
7950 /*
7951 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7952 * contribution. If @p migrates from another CPU to @cpu add its
7953 * contribution. In all the other cases @cpu is not impacted by the
7954 * migration so its util_avg is already correct.
7955 */
7956 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7957 lsub_positive(&util, task_util(p));
7958 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7959 util += task_util(p);
7960
7961 if (sched_feat(UTIL_EST)) {
7962 unsigned long util_est;
7963
7964 util_est = READ_ONCE(cfs_rq->avg.util_est);
7965
7966 /*
7967 * During wake-up @p isn't enqueued yet and doesn't contribute
7968 * to any cpu_rq(cpu)->cfs.avg.util_est.
7969 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7970 * has been enqueued.
7971 *
7972 * During exec (@dst_cpu = -1) @p is enqueued and does
7973 * contribute to cpu_rq(cpu)->cfs.util_est.
7974 * Remove it to "simulate" cpu_util without @p's contribution.
7975 *
7976 * Despite the task_on_rq_queued(@p) check there is still a
7977 * small window for a possible race when an exec
7978 * select_task_rq_fair() races with LB's detach_task().
7979 *
7980 * detach_task()
7981 * deactivate_task()
7982 * p->on_rq = TASK_ON_RQ_MIGRATING;
7983 * -------------------------------- A
7984 * dequeue_task() \
7985 * dequeue_task_fair() + Race Time
7986 * util_est_dequeue() /
7987 * -------------------------------- B
7988 *
7989 * The additional check "current == p" is required to further
7990 * reduce the race window.
7991 */
7992 if (dst_cpu == cpu)
7993 util_est += _task_util_est(p);
7994 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7995 lsub_positive(&util_est, _task_util_est(p));
7996
7997 util = max(util, util_est);
7998 }
7999
8000 return min(util, arch_scale_cpu_capacity(cpu));
8001 }
8002
cpu_util_cfs(int cpu)8003 unsigned long cpu_util_cfs(int cpu)
8004 {
8005 return cpu_util(cpu, NULL, -1, 0);
8006 }
8007
cpu_util_cfs_boost(int cpu)8008 unsigned long cpu_util_cfs_boost(int cpu)
8009 {
8010 return cpu_util(cpu, NULL, -1, 1);
8011 }
8012
8013 /*
8014 * cpu_util_without: compute cpu utilization without any contributions from *p
8015 * @cpu: the CPU which utilization is requested
8016 * @p: the task which utilization should be discounted
8017 *
8018 * The utilization of a CPU is defined by the utilization of tasks currently
8019 * enqueued on that CPU as well as tasks which are currently sleeping after an
8020 * execution on that CPU.
8021 *
8022 * This method returns the utilization of the specified CPU by discounting the
8023 * utilization of the specified task, whenever the task is currently
8024 * contributing to the CPU utilization.
8025 */
cpu_util_without(int cpu,struct task_struct * p)8026 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8027 {
8028 /* Task has no contribution or is new */
8029 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8030 p = NULL;
8031
8032 return cpu_util(cpu, p, -1, 0);
8033 }
8034
8035 /*
8036 * This function computes an effective utilization for the given CPU, to be
8037 * used for frequency selection given the linear relation: f = u * f_max.
8038 *
8039 * The scheduler tracks the following metrics:
8040 *
8041 * cpu_util_{cfs,rt,dl,irq}()
8042 * cpu_bw_dl()
8043 *
8044 * Where the cfs,rt and dl util numbers are tracked with the same metric and
8045 * synchronized windows and are thus directly comparable.
8046 *
8047 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8048 * which excludes things like IRQ and steal-time. These latter are then accrued
8049 * in the IRQ utilization.
8050 *
8051 * The DL bandwidth number OTOH is not a measured metric but a value computed
8052 * based on the task model parameters and gives the minimal utilization
8053 * required to meet deadlines.
8054 */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)8055 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8056 unsigned long *min,
8057 unsigned long *max)
8058 {
8059 unsigned long util, irq, scale;
8060 struct rq *rq = cpu_rq(cpu);
8061
8062 scale = arch_scale_cpu_capacity(cpu);
8063
8064 /*
8065 * Early check to see if IRQ/steal time saturates the CPU, can be
8066 * because of inaccuracies in how we track these -- see
8067 * update_irq_load_avg().
8068 */
8069 irq = cpu_util_irq(rq);
8070 if (unlikely(irq >= scale)) {
8071 if (min)
8072 *min = scale;
8073 if (max)
8074 *max = scale;
8075 return scale;
8076 }
8077
8078 if (min) {
8079 /*
8080 * The minimum utilization returns the highest level between:
8081 * - the computed DL bandwidth needed with the IRQ pressure which
8082 * steals time to the deadline task.
8083 * - The minimum performance requirement for CFS and/or RT.
8084 */
8085 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8086
8087 /*
8088 * When an RT task is runnable and uclamp is not used, we must
8089 * ensure that the task will run at maximum compute capacity.
8090 */
8091 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8092 *min = max(*min, scale);
8093 }
8094
8095 /*
8096 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8097 * CFS tasks and we use the same metric to track the effective
8098 * utilization (PELT windows are synchronized) we can directly add them
8099 * to obtain the CPU's actual utilization.
8100 */
8101 util = util_cfs + cpu_util_rt(rq);
8102 util += cpu_util_dl(rq);
8103
8104 /*
8105 * The maximum hint is a soft bandwidth requirement, which can be lower
8106 * than the actual utilization because of uclamp_max requirements.
8107 */
8108 if (max)
8109 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8110
8111 if (util >= scale)
8112 return scale;
8113
8114 /*
8115 * There is still idle time; further improve the number by using the
8116 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8117 * need to scale the task numbers:
8118 *
8119 * max - irq
8120 * U' = irq + --------- * U
8121 * max
8122 */
8123 util = scale_irq_capacity(util, irq, scale);
8124 util += irq;
8125
8126 return min(scale, util);
8127 }
8128
sched_cpu_util(int cpu)8129 unsigned long sched_cpu_util(int cpu)
8130 {
8131 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8132 }
8133
8134 /*
8135 * energy_env - Utilization landscape for energy estimation.
8136 * @task_busy_time: Utilization contribution by the task for which we test the
8137 * placement. Given by eenv_task_busy_time().
8138 * @pd_busy_time: Utilization of the whole perf domain without the task
8139 * contribution. Given by eenv_pd_busy_time().
8140 * @cpu_cap: Maximum CPU capacity for the perf domain.
8141 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8142 */
8143 struct energy_env {
8144 unsigned long task_busy_time;
8145 unsigned long pd_busy_time;
8146 unsigned long cpu_cap;
8147 unsigned long pd_cap;
8148 };
8149
8150 /*
8151 * Compute the task busy time for compute_energy(). This time cannot be
8152 * injected directly into effective_cpu_util() because of the IRQ scaling.
8153 * The latter only makes sense with the most recent CPUs where the task has
8154 * run.
8155 */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8156 static inline void eenv_task_busy_time(struct energy_env *eenv,
8157 struct task_struct *p, int prev_cpu)
8158 {
8159 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8160 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8161
8162 if (unlikely(irq >= max_cap))
8163 busy_time = max_cap;
8164 else
8165 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8166
8167 eenv->task_busy_time = busy_time;
8168 }
8169
8170 /*
8171 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8172 * utilization for each @pd_cpus, it however doesn't take into account
8173 * clamping since the ratio (utilization / cpu_capacity) is already enough to
8174 * scale the EM reported power consumption at the (eventually clamped)
8175 * cpu_capacity.
8176 *
8177 * The contribution of the task @p for which we want to estimate the
8178 * energy cost is removed (by cpu_util()) and must be calculated
8179 * separately (see eenv_task_busy_time). This ensures:
8180 *
8181 * - A stable PD utilization, no matter which CPU of that PD we want to place
8182 * the task on.
8183 *
8184 * - A fair comparison between CPUs as the task contribution (task_util())
8185 * will always be the same no matter which CPU utilization we rely on
8186 * (util_avg or util_est).
8187 *
8188 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8189 * exceed @eenv->pd_cap.
8190 */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8191 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8192 struct cpumask *pd_cpus,
8193 struct task_struct *p)
8194 {
8195 unsigned long busy_time = 0;
8196 int cpu;
8197
8198 for_each_cpu(cpu, pd_cpus) {
8199 unsigned long util = cpu_util(cpu, p, -1, 0);
8200
8201 busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8202 }
8203
8204 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8205 }
8206
8207 /*
8208 * Compute the maximum utilization for compute_energy() when the task @p
8209 * is placed on the cpu @dst_cpu.
8210 *
8211 * Returns the maximum utilization among @eenv->cpus. This utilization can't
8212 * exceed @eenv->cpu_cap.
8213 */
8214 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8215 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8216 struct task_struct *p, int dst_cpu)
8217 {
8218 unsigned long max_util = 0;
8219 int cpu;
8220
8221 for_each_cpu(cpu, pd_cpus) {
8222 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8223 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8224 unsigned long eff_util, min, max;
8225
8226 /*
8227 * Performance domain frequency: utilization clamping
8228 * must be considered since it affects the selection
8229 * of the performance domain frequency.
8230 * NOTE: in case RT tasks are running, by default the min
8231 * utilization can be max OPP.
8232 */
8233 eff_util = effective_cpu_util(cpu, util, &min, &max);
8234
8235 /* Task's uclamp can modify min and max value */
8236 if (tsk && uclamp_is_used()) {
8237 min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8238
8239 /*
8240 * If there is no active max uclamp constraint,
8241 * directly use task's one, otherwise keep max.
8242 */
8243 if (uclamp_rq_is_idle(cpu_rq(cpu)))
8244 max = uclamp_eff_value(p, UCLAMP_MAX);
8245 else
8246 max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8247 }
8248
8249 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8250 max_util = max(max_util, eff_util);
8251 }
8252
8253 return min(max_util, eenv->cpu_cap);
8254 }
8255
8256 /*
8257 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8258 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8259 * contribution is ignored.
8260 */
8261 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)8262 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8263 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8264 {
8265 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8266 unsigned long busy_time = eenv->pd_busy_time;
8267 unsigned long energy;
8268
8269 if (dst_cpu >= 0)
8270 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8271
8272 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8273
8274 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8275
8276 return energy;
8277 }
8278
8279 /*
8280 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8281 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8282 * spare capacity in each performance domain and uses it as a potential
8283 * candidate to execute the task. Then, it uses the Energy Model to figure
8284 * out which of the CPU candidates is the most energy-efficient.
8285 *
8286 * The rationale for this heuristic is as follows. In a performance domain,
8287 * all the most energy efficient CPU candidates (according to the Energy
8288 * Model) are those for which we'll request a low frequency. When there are
8289 * several CPUs for which the frequency request will be the same, we don't
8290 * have enough data to break the tie between them, because the Energy Model
8291 * only includes active power costs. With this model, if we assume that
8292 * frequency requests follow utilization (e.g. using schedutil), the CPU with
8293 * the maximum spare capacity in a performance domain is guaranteed to be among
8294 * the best candidates of the performance domain.
8295 *
8296 * In practice, it could be preferable from an energy standpoint to pack
8297 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8298 * but that could also hurt our chances to go cluster idle, and we have no
8299 * ways to tell with the current Energy Model if this is actually a good
8300 * idea or not. So, find_energy_efficient_cpu() basically favors
8301 * cluster-packing, and spreading inside a cluster. That should at least be
8302 * a good thing for latency, and this is consistent with the idea that most
8303 * of the energy savings of EAS come from the asymmetry of the system, and
8304 * not so much from breaking the tie between identical CPUs. That's also the
8305 * reason why EAS is enabled in the topology code only for systems where
8306 * SD_ASYM_CPUCAPACITY is set.
8307 *
8308 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8309 * they don't have any useful utilization data yet and it's not possible to
8310 * forecast their impact on energy consumption. Consequently, they will be
8311 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8312 * to be energy-inefficient in some use-cases. The alternative would be to
8313 * bias new tasks towards specific types of CPUs first, or to try to infer
8314 * their util_avg from the parent task, but those heuristics could hurt
8315 * other use-cases too. So, until someone finds a better way to solve this,
8316 * let's keep things simple by re-using the existing slow path.
8317 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)8318 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8319 {
8320 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8321 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8322 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8323 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8324 struct root_domain *rd = this_rq()->rd;
8325 int cpu, best_energy_cpu, target = -1;
8326 int prev_fits = -1, best_fits = -1;
8327 unsigned long best_actual_cap = 0;
8328 unsigned long prev_actual_cap = 0;
8329 struct sched_domain *sd;
8330 struct perf_domain *pd;
8331 struct energy_env eenv;
8332
8333 rcu_read_lock();
8334 pd = rcu_dereference(rd->pd);
8335 if (!pd)
8336 goto unlock;
8337
8338 /*
8339 * Energy-aware wake-up happens on the lowest sched_domain starting
8340 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8341 */
8342 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
8343 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8344 sd = sd->parent;
8345 if (!sd)
8346 goto unlock;
8347
8348 target = prev_cpu;
8349
8350 sync_entity_load_avg(&p->se);
8351 if (!task_util_est(p) && p_util_min == 0)
8352 goto unlock;
8353
8354 eenv_task_busy_time(&eenv, p, prev_cpu);
8355
8356 for (; pd; pd = pd->next) {
8357 unsigned long util_min = p_util_min, util_max = p_util_max;
8358 unsigned long cpu_cap, cpu_actual_cap, util;
8359 long prev_spare_cap = -1, max_spare_cap = -1;
8360 unsigned long rq_util_min, rq_util_max;
8361 unsigned long cur_delta, base_energy;
8362 int max_spare_cap_cpu = -1;
8363 int fits, max_fits = -1;
8364
8365 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
8366
8367 if (cpumask_empty(cpus))
8368 continue;
8369
8370 /* Account external pressure for the energy estimation */
8371 cpu = cpumask_first(cpus);
8372 cpu_actual_cap = get_actual_cpu_capacity(cpu);
8373
8374 eenv.cpu_cap = cpu_actual_cap;
8375 eenv.pd_cap = 0;
8376
8377 for_each_cpu(cpu, cpus) {
8378 struct rq *rq = cpu_rq(cpu);
8379
8380 eenv.pd_cap += cpu_actual_cap;
8381
8382 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8383 continue;
8384
8385 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8386 continue;
8387
8388 util = cpu_util(cpu, p, cpu, 0);
8389 cpu_cap = capacity_of(cpu);
8390
8391 /*
8392 * Skip CPUs that cannot satisfy the capacity request.
8393 * IOW, placing the task there would make the CPU
8394 * overutilized. Take uclamp into account to see how
8395 * much capacity we can get out of the CPU; this is
8396 * aligned with sched_cpu_util().
8397 */
8398 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8399 /*
8400 * Open code uclamp_rq_util_with() except for
8401 * the clamp() part. I.e.: apply max aggregation
8402 * only. util_fits_cpu() logic requires to
8403 * operate on non clamped util but must use the
8404 * max-aggregated uclamp_{min, max}.
8405 */
8406 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8407 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8408
8409 util_min = max(rq_util_min, p_util_min);
8410 util_max = max(rq_util_max, p_util_max);
8411 }
8412
8413 fits = util_fits_cpu(util, util_min, util_max, cpu);
8414 if (!fits)
8415 continue;
8416
8417 lsub_positive(&cpu_cap, util);
8418
8419 if (cpu == prev_cpu) {
8420 /* Always use prev_cpu as a candidate. */
8421 prev_spare_cap = cpu_cap;
8422 prev_fits = fits;
8423 } else if ((fits > max_fits) ||
8424 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8425 /*
8426 * Find the CPU with the maximum spare capacity
8427 * among the remaining CPUs in the performance
8428 * domain.
8429 */
8430 max_spare_cap = cpu_cap;
8431 max_spare_cap_cpu = cpu;
8432 max_fits = fits;
8433 }
8434 }
8435
8436 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8437 continue;
8438
8439 eenv_pd_busy_time(&eenv, cpus, p);
8440 /* Compute the 'base' energy of the pd, without @p */
8441 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8442
8443 /* Evaluate the energy impact of using prev_cpu. */
8444 if (prev_spare_cap > -1) {
8445 prev_delta = compute_energy(&eenv, pd, cpus, p,
8446 prev_cpu);
8447 /* CPU utilization has changed */
8448 if (prev_delta < base_energy)
8449 goto unlock;
8450 prev_delta -= base_energy;
8451 prev_actual_cap = cpu_actual_cap;
8452 best_delta = min(best_delta, prev_delta);
8453 }
8454
8455 /* Evaluate the energy impact of using max_spare_cap_cpu. */
8456 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8457 /* Current best energy cpu fits better */
8458 if (max_fits < best_fits)
8459 continue;
8460
8461 /*
8462 * Both don't fit performance hint (i.e. uclamp_min)
8463 * but best energy cpu has better capacity.
8464 */
8465 if ((max_fits < 0) &&
8466 (cpu_actual_cap <= best_actual_cap))
8467 continue;
8468
8469 cur_delta = compute_energy(&eenv, pd, cpus, p,
8470 max_spare_cap_cpu);
8471 /* CPU utilization has changed */
8472 if (cur_delta < base_energy)
8473 goto unlock;
8474 cur_delta -= base_energy;
8475
8476 /*
8477 * Both fit for the task but best energy cpu has lower
8478 * energy impact.
8479 */
8480 if ((max_fits > 0) && (best_fits > 0) &&
8481 (cur_delta >= best_delta))
8482 continue;
8483
8484 best_delta = cur_delta;
8485 best_energy_cpu = max_spare_cap_cpu;
8486 best_fits = max_fits;
8487 best_actual_cap = cpu_actual_cap;
8488 }
8489 }
8490 rcu_read_unlock();
8491
8492 if ((best_fits > prev_fits) ||
8493 ((best_fits > 0) && (best_delta < prev_delta)) ||
8494 ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8495 target = best_energy_cpu;
8496
8497 return target;
8498
8499 unlock:
8500 rcu_read_unlock();
8501
8502 return target;
8503 }
8504
8505 /*
8506 * select_task_rq_fair: Select target runqueue for the waking task in domains
8507 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8508 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8509 *
8510 * Balances load by selecting the idlest CPU in the idlest group, or under
8511 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8512 *
8513 * Returns the target CPU number.
8514 */
8515 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8516 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8517 {
8518 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8519 struct sched_domain *tmp, *sd = NULL;
8520 int cpu = smp_processor_id();
8521 int new_cpu = prev_cpu;
8522 int want_affine = 0;
8523 /* SD_flags and WF_flags share the first nibble */
8524 int sd_flag = wake_flags & 0xF;
8525
8526 /*
8527 * required for stable ->cpus_allowed
8528 */
8529 lockdep_assert_held(&p->pi_lock);
8530 if (wake_flags & WF_TTWU) {
8531 record_wakee(p);
8532
8533 if ((wake_flags & WF_CURRENT_CPU) &&
8534 cpumask_test_cpu(cpu, p->cpus_ptr))
8535 return cpu;
8536
8537 if (!is_rd_overutilized(this_rq()->rd)) {
8538 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8539 if (new_cpu >= 0)
8540 return new_cpu;
8541 new_cpu = prev_cpu;
8542 }
8543
8544 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8545 }
8546
8547 rcu_read_lock();
8548 for_each_domain(cpu, tmp) {
8549 /*
8550 * If both 'cpu' and 'prev_cpu' are part of this domain,
8551 * cpu is a valid SD_WAKE_AFFINE target.
8552 */
8553 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8554 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8555 if (cpu != prev_cpu)
8556 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8557
8558 sd = NULL; /* Prefer wake_affine over balance flags */
8559 break;
8560 }
8561
8562 /*
8563 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8564 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8565 * will usually go to the fast path.
8566 */
8567 if (tmp->flags & sd_flag)
8568 sd = tmp;
8569 else if (!want_affine)
8570 break;
8571 }
8572
8573 if (unlikely(sd)) {
8574 /* Slow path */
8575 new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8576 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
8577 /* Fast path */
8578 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8579 }
8580 rcu_read_unlock();
8581
8582 return new_cpu;
8583 }
8584
8585 /*
8586 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8587 * cfs_rq_of(p) references at time of call are still valid and identify the
8588 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8589 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8590 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8591 {
8592 struct sched_entity *se = &p->se;
8593
8594 if (!task_on_rq_migrating(p)) {
8595 remove_entity_load_avg(se);
8596
8597 /*
8598 * Here, the task's PELT values have been updated according to
8599 * the current rq's clock. But if that clock hasn't been
8600 * updated in a while, a substantial idle time will be missed,
8601 * leading to an inflation after wake-up on the new rq.
8602 *
8603 * Estimate the missing time from the cfs_rq last_update_time
8604 * and update sched_avg to improve the PELT continuity after
8605 * migration.
8606 */
8607 migrate_se_pelt_lag(se);
8608 }
8609
8610 /* Tell new CPU we are migrated */
8611 se->avg.last_update_time = 0;
8612
8613 update_scan_period(p, new_cpu);
8614 }
8615
task_dead_fair(struct task_struct * p)8616 static void task_dead_fair(struct task_struct *p)
8617 {
8618 struct sched_entity *se = &p->se;
8619
8620 if (se->sched_delayed) {
8621 struct rq_flags rf;
8622 struct rq *rq;
8623
8624 rq = task_rq_lock(p, &rf);
8625 if (se->sched_delayed) {
8626 update_rq_clock(rq);
8627 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8628 }
8629 task_rq_unlock(rq, p, &rf);
8630 }
8631
8632 remove_entity_load_avg(se);
8633 }
8634
8635 /*
8636 * Set the max capacity the task is allowed to run at for misfit detection.
8637 */
set_task_max_allowed_capacity(struct task_struct * p)8638 static void set_task_max_allowed_capacity(struct task_struct *p)
8639 {
8640 struct asym_cap_data *entry;
8641
8642 if (!sched_asym_cpucap_active())
8643 return;
8644
8645 rcu_read_lock();
8646 list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8647 cpumask_t *cpumask;
8648
8649 cpumask = cpu_capacity_span(entry);
8650 if (!cpumask_intersects(p->cpus_ptr, cpumask))
8651 continue;
8652
8653 p->max_allowed_capacity = entry->capacity;
8654 break;
8655 }
8656 rcu_read_unlock();
8657 }
8658
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)8659 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8660 {
8661 set_cpus_allowed_common(p, ctx);
8662 set_task_max_allowed_capacity(p);
8663 }
8664
set_next_buddy(struct sched_entity * se)8665 static void set_next_buddy(struct sched_entity *se)
8666 {
8667 for_each_sched_entity(se) {
8668 if (WARN_ON_ONCE(!se->on_rq))
8669 return;
8670 if (se_is_idle(se))
8671 return;
8672 cfs_rq_of(se)->next = se;
8673 }
8674 }
8675
8676 enum preempt_wakeup_action {
8677 PREEMPT_WAKEUP_NONE, /* No preemption. */
8678 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */
8679 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */
8680 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */
8681 };
8682
8683 static inline bool
set_preempt_buddy(struct cfs_rq * cfs_rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8684 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags,
8685 struct sched_entity *pse, struct sched_entity *se)
8686 {
8687 /*
8688 * Keep existing buddy if the deadline is sooner than pse.
8689 * The older buddy may be cache cold and completely unrelated
8690 * to the current wakeup but that is unpredictable where as
8691 * obeying the deadline is more in line with EEVDF objectives.
8692 */
8693 if (cfs_rq->next && entity_before(cfs_rq->next, pse))
8694 return false;
8695
8696 set_next_buddy(pse);
8697 return true;
8698 }
8699
8700 /*
8701 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
8702 * strictly enforced because the hint is either misunderstood or
8703 * multiple tasks must be woken up.
8704 */
8705 static inline enum preempt_wakeup_action
preempt_sync(struct rq * rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8706 preempt_sync(struct rq *rq, int wake_flags,
8707 struct sched_entity *pse, struct sched_entity *se)
8708 {
8709 u64 threshold, delta;
8710
8711 /*
8712 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
8713 * though it is likely harmless.
8714 */
8715 WARN_ON_ONCE(!(wake_flags & WF_TTWU));
8716
8717 threshold = sysctl_sched_migration_cost;
8718 delta = rq_clock_task(rq) - se->exec_start;
8719 if ((s64)delta < 0)
8720 delta = 0;
8721
8722 /*
8723 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
8724 * could run on other CPUs. Reduce the threshold before preemption is
8725 * allowed to an arbitrary lower value as it is more likely (but not
8726 * guaranteed) the waker requires the wakee to finish.
8727 */
8728 if (wake_flags & WF_RQ_SELECTED)
8729 threshold >>= 2;
8730
8731 /*
8732 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
8733 * wakeups to be issued.
8734 */
8735 if (entity_before(pse, se) && delta >= threshold)
8736 return PREEMPT_WAKEUP_RESCHED;
8737
8738 return PREEMPT_WAKEUP_NONE;
8739 }
8740
8741 /*
8742 * Preempt the current task with a newly woken task if needed:
8743 */
check_preempt_wakeup_fair(struct rq * rq,struct task_struct * p,int wake_flags)8744 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8745 {
8746 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
8747 struct task_struct *donor = rq->donor;
8748 struct sched_entity *se = &donor->se, *pse = &p->se;
8749 struct cfs_rq *cfs_rq = task_cfs_rq(donor);
8750 int cse_is_idle, pse_is_idle;
8751
8752 if (unlikely(se == pse))
8753 return;
8754
8755 /*
8756 * This is possible from callers such as attach_tasks(), in which we
8757 * unconditionally wakeup_preempt() after an enqueue (which may have
8758 * lead to a throttle). This both saves work and prevents false
8759 * next-buddy nomination below.
8760 */
8761 if (task_is_throttled(p))
8762 return;
8763
8764 /*
8765 * We can come here with TIF_NEED_RESCHED already set from new task
8766 * wake up path.
8767 *
8768 * Note: this also catches the edge-case of curr being in a throttled
8769 * group (e.g. via set_curr_task), since update_curr() (in the
8770 * enqueue of curr) will have resulted in resched being set. This
8771 * prevents us from potentially nominating it as a false LAST_BUDDY
8772 * below.
8773 */
8774 if (test_tsk_need_resched(rq->curr))
8775 return;
8776
8777 if (!sched_feat(WAKEUP_PREEMPTION))
8778 return;
8779
8780 find_matching_se(&se, &pse);
8781 WARN_ON_ONCE(!pse);
8782
8783 cse_is_idle = se_is_idle(se);
8784 pse_is_idle = se_is_idle(pse);
8785
8786 /*
8787 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
8788 * in the inverse case).
8789 */
8790 if (cse_is_idle && !pse_is_idle) {
8791 /*
8792 * When non-idle entity preempt an idle entity,
8793 * don't give idle entity slice protection.
8794 */
8795 preempt_action = PREEMPT_WAKEUP_SHORT;
8796 goto preempt;
8797 }
8798
8799 if (cse_is_idle != pse_is_idle)
8800 return;
8801
8802 /*
8803 * BATCH and IDLE tasks do not preempt others.
8804 */
8805 if (unlikely(!normal_policy(p->policy)))
8806 return;
8807
8808 cfs_rq = cfs_rq_of(se);
8809 update_curr(cfs_rq);
8810 /*
8811 * If @p has a shorter slice than current and @p is eligible, override
8812 * current's slice protection in order to allow preemption.
8813 */
8814 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
8815 preempt_action = PREEMPT_WAKEUP_SHORT;
8816 goto pick;
8817 }
8818
8819 /*
8820 * Ignore wakee preemption on WF_FORK as it is less likely that
8821 * there is shared data as exec often follow fork. Do not
8822 * preempt for tasks that are sched_delayed as it would violate
8823 * EEVDF to forcibly queue an ineligible task.
8824 */
8825 if ((wake_flags & WF_FORK) || pse->sched_delayed)
8826 return;
8827
8828 /*
8829 * If @p potentially is completing work required by current then
8830 * consider preemption.
8831 *
8832 * Reschedule if waker is no longer eligible. */
8833 if (in_task() && !entity_eligible(cfs_rq, se)) {
8834 preempt_action = PREEMPT_WAKEUP_RESCHED;
8835 goto preempt;
8836 }
8837
8838 /* Prefer picking wakee soon if appropriate. */
8839 if (sched_feat(NEXT_BUDDY) &&
8840 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) {
8841
8842 /*
8843 * Decide whether to obey WF_SYNC hint for a new buddy. Old
8844 * buddies are ignored as they may not be relevant to the
8845 * waker and less likely to be cache hot.
8846 */
8847 if (wake_flags & WF_SYNC)
8848 preempt_action = preempt_sync(rq, wake_flags, pse, se);
8849 }
8850
8851 switch (preempt_action) {
8852 case PREEMPT_WAKEUP_NONE:
8853 return;
8854 case PREEMPT_WAKEUP_RESCHED:
8855 goto preempt;
8856 case PREEMPT_WAKEUP_SHORT:
8857 fallthrough;
8858 case PREEMPT_WAKEUP_PICK:
8859 break;
8860 }
8861
8862 pick:
8863 /*
8864 * If @p has become the most eligible task, force preemption.
8865 */
8866 if (__pick_eevdf(cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT) == pse)
8867 goto preempt;
8868
8869 if (sched_feat(RUN_TO_PARITY))
8870 update_protect_slice(cfs_rq, se);
8871
8872 return;
8873
8874 preempt:
8875 if (preempt_action == PREEMPT_WAKEUP_SHORT)
8876 cancel_protect_slice(se);
8877
8878 resched_curr_lazy(rq);
8879 }
8880
pick_task_fair(struct rq * rq,struct rq_flags * rf)8881 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
8882 {
8883 struct sched_entity *se;
8884 struct cfs_rq *cfs_rq;
8885 struct task_struct *p;
8886 bool throttled;
8887
8888 again:
8889 cfs_rq = &rq->cfs;
8890 if (!cfs_rq->nr_queued)
8891 return NULL;
8892
8893 throttled = false;
8894
8895 do {
8896 /* Might not have done put_prev_entity() */
8897 if (cfs_rq->curr && cfs_rq->curr->on_rq)
8898 update_curr(cfs_rq);
8899
8900 throttled |= check_cfs_rq_runtime(cfs_rq);
8901
8902 se = pick_next_entity(rq, cfs_rq);
8903 if (!se)
8904 goto again;
8905 cfs_rq = group_cfs_rq(se);
8906 } while (cfs_rq);
8907
8908 p = task_of(se);
8909 if (unlikely(throttled))
8910 task_throttle_setup_work(p);
8911 return p;
8912 }
8913
8914 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8915 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8916
8917 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8918 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8919 {
8920 struct sched_entity *se;
8921 struct task_struct *p;
8922 int new_tasks;
8923
8924 again:
8925 p = pick_task_fair(rq, rf);
8926 if (!p)
8927 goto idle;
8928 se = &p->se;
8929
8930 #ifdef CONFIG_FAIR_GROUP_SCHED
8931 if (prev->sched_class != &fair_sched_class)
8932 goto simple;
8933
8934 __put_prev_set_next_dl_server(rq, prev, p);
8935
8936 /*
8937 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8938 * likely that a next task is from the same cgroup as the current.
8939 *
8940 * Therefore attempt to avoid putting and setting the entire cgroup
8941 * hierarchy, only change the part that actually changes.
8942 *
8943 * Since we haven't yet done put_prev_entity and if the selected task
8944 * is a different task than we started out with, try and touch the
8945 * least amount of cfs_rqs.
8946 */
8947 if (prev != p) {
8948 struct sched_entity *pse = &prev->se;
8949 struct cfs_rq *cfs_rq;
8950
8951 while (!(cfs_rq = is_same_group(se, pse))) {
8952 int se_depth = se->depth;
8953 int pse_depth = pse->depth;
8954
8955 if (se_depth <= pse_depth) {
8956 put_prev_entity(cfs_rq_of(pse), pse);
8957 pse = parent_entity(pse);
8958 }
8959 if (se_depth >= pse_depth) {
8960 set_next_entity(cfs_rq_of(se), se);
8961 se = parent_entity(se);
8962 }
8963 }
8964
8965 put_prev_entity(cfs_rq, pse);
8966 set_next_entity(cfs_rq, se);
8967
8968 __set_next_task_fair(rq, p, true);
8969 }
8970
8971 return p;
8972
8973 simple:
8974 #endif /* CONFIG_FAIR_GROUP_SCHED */
8975 put_prev_set_next_task(rq, prev, p);
8976 return p;
8977
8978 idle:
8979 if (rf) {
8980 new_tasks = sched_balance_newidle(rq, rf);
8981
8982 /*
8983 * Because sched_balance_newidle() releases (and re-acquires)
8984 * rq->lock, it is possible for any higher priority task to
8985 * appear. In that case we must re-start the pick_next_entity()
8986 * loop.
8987 */
8988 if (new_tasks < 0)
8989 return RETRY_TASK;
8990
8991 if (new_tasks > 0)
8992 goto again;
8993 }
8994
8995 /*
8996 * rq is about to be idle, check if we need to update the
8997 * lost_idle_time of clock_pelt
8998 */
8999 update_idle_rq_clock_pelt(rq);
9000
9001 return NULL;
9002 }
9003
9004 static struct task_struct *
fair_server_pick_task(struct sched_dl_entity * dl_se,struct rq_flags * rf)9005 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
9006 {
9007 return pick_task_fair(dl_se->rq, rf);
9008 }
9009
fair_server_init(struct rq * rq)9010 void fair_server_init(struct rq *rq)
9011 {
9012 struct sched_dl_entity *dl_se = &rq->fair_server;
9013
9014 init_dl_entity(dl_se);
9015
9016 dl_server_init(dl_se, rq, fair_server_pick_task);
9017 }
9018
9019 /*
9020 * Account for a descheduled task:
9021 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)9022 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
9023 {
9024 struct sched_entity *se = &prev->se;
9025 struct cfs_rq *cfs_rq;
9026
9027 for_each_sched_entity(se) {
9028 cfs_rq = cfs_rq_of(se);
9029 put_prev_entity(cfs_rq, se);
9030 }
9031 }
9032
9033 /*
9034 * sched_yield() is very simple
9035 */
yield_task_fair(struct rq * rq)9036 static void yield_task_fair(struct rq *rq)
9037 {
9038 struct task_struct *curr = rq->donor;
9039 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
9040 struct sched_entity *se = &curr->se;
9041
9042 /*
9043 * Are we the only task in the tree?
9044 */
9045 if (unlikely(rq->nr_running == 1))
9046 return;
9047
9048 clear_buddies(cfs_rq, se);
9049
9050 update_rq_clock(rq);
9051 /*
9052 * Update run-time statistics of the 'current'.
9053 */
9054 update_curr(cfs_rq);
9055 /*
9056 * Tell update_rq_clock() that we've just updated,
9057 * so we don't do microscopic update in schedule()
9058 * and double the fastpath cost.
9059 */
9060 rq_clock_skip_update(rq);
9061
9062 /*
9063 * Forfeit the remaining vruntime, only if the entity is eligible. This
9064 * condition is necessary because in core scheduling we prefer to run
9065 * ineligible tasks rather than force idling. If this happens we may
9066 * end up in a loop where the core scheduler picks the yielding task,
9067 * which yields immediately again; without the condition the vruntime
9068 * ends up quickly running away.
9069 */
9070 if (entity_eligible(cfs_rq, se)) {
9071 se->vruntime = se->deadline;
9072 se->deadline += calc_delta_fair(se->slice, se);
9073 }
9074 }
9075
yield_to_task_fair(struct rq * rq,struct task_struct * p)9076 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9077 {
9078 struct sched_entity *se = &p->se;
9079
9080 /* !se->on_rq also covers throttled task */
9081 if (!se->on_rq)
9082 return false;
9083
9084 /* Tell the scheduler that we'd really like se to run next. */
9085 set_next_buddy(se);
9086
9087 yield_task_fair(rq);
9088
9089 return true;
9090 }
9091
9092 /**************************************************
9093 * Fair scheduling class load-balancing methods.
9094 *
9095 * BASICS
9096 *
9097 * The purpose of load-balancing is to achieve the same basic fairness the
9098 * per-CPU scheduler provides, namely provide a proportional amount of compute
9099 * time to each task. This is expressed in the following equation:
9100 *
9101 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
9102 *
9103 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9104 * W_i,0 is defined as:
9105 *
9106 * W_i,0 = \Sum_j w_i,j (2)
9107 *
9108 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9109 * is derived from the nice value as per sched_prio_to_weight[].
9110 *
9111 * The weight average is an exponential decay average of the instantaneous
9112 * weight:
9113 *
9114 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
9115 *
9116 * C_i is the compute capacity of CPU i, typically it is the
9117 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9118 * can also include other factors [XXX].
9119 *
9120 * To achieve this balance we define a measure of imbalance which follows
9121 * directly from (1):
9122 *
9123 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
9124 *
9125 * We them move tasks around to minimize the imbalance. In the continuous
9126 * function space it is obvious this converges, in the discrete case we get
9127 * a few fun cases generally called infeasible weight scenarios.
9128 *
9129 * [XXX expand on:
9130 * - infeasible weights;
9131 * - local vs global optima in the discrete case. ]
9132 *
9133 *
9134 * SCHED DOMAINS
9135 *
9136 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9137 * for all i,j solution, we create a tree of CPUs that follows the hardware
9138 * topology where each level pairs two lower groups (or better). This results
9139 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9140 * tree to only the first of the previous level and we decrease the frequency
9141 * of load-balance at each level inversely proportional to the number of CPUs in
9142 * the groups.
9143 *
9144 * This yields:
9145 *
9146 * log_2 n 1 n
9147 * \Sum { --- * --- * 2^i } = O(n) (5)
9148 * i = 0 2^i 2^i
9149 * `- size of each group
9150 * | | `- number of CPUs doing load-balance
9151 * | `- freq
9152 * `- sum over all levels
9153 *
9154 * Coupled with a limit on how many tasks we can migrate every balance pass,
9155 * this makes (5) the runtime complexity of the balancer.
9156 *
9157 * An important property here is that each CPU is still (indirectly) connected
9158 * to every other CPU in at most O(log n) steps:
9159 *
9160 * The adjacency matrix of the resulting graph is given by:
9161 *
9162 * log_2 n
9163 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
9164 * k = 0
9165 *
9166 * And you'll find that:
9167 *
9168 * A^(log_2 n)_i,j != 0 for all i,j (7)
9169 *
9170 * Showing there's indeed a path between every CPU in at most O(log n) steps.
9171 * The task movement gives a factor of O(m), giving a convergence complexity
9172 * of:
9173 *
9174 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
9175 *
9176 *
9177 * WORK CONSERVING
9178 *
9179 * In order to avoid CPUs going idle while there's still work to do, new idle
9180 * balancing is more aggressive and has the newly idle CPU iterate up the domain
9181 * tree itself instead of relying on other CPUs to bring it work.
9182 *
9183 * This adds some complexity to both (5) and (8) but it reduces the total idle
9184 * time.
9185 *
9186 * [XXX more?]
9187 *
9188 *
9189 * CGROUPS
9190 *
9191 * Cgroups make a horror show out of (2), instead of a simple sum we get:
9192 *
9193 * s_k,i
9194 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
9195 * S_k
9196 *
9197 * Where
9198 *
9199 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
9200 *
9201 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9202 *
9203 * The big problem is S_k, its a global sum needed to compute a local (W_i)
9204 * property.
9205 *
9206 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9207 * rewrite all of this once again.]
9208 */
9209
9210 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9211
9212 enum fbq_type { regular, remote, all };
9213
9214 /*
9215 * 'group_type' describes the group of CPUs at the moment of load balancing.
9216 *
9217 * The enum is ordered by pulling priority, with the group with lowest priority
9218 * first so the group_type can simply be compared when selecting the busiest
9219 * group. See update_sd_pick_busiest().
9220 */
9221 enum group_type {
9222 /* The group has spare capacity that can be used to run more tasks. */
9223 group_has_spare = 0,
9224 /*
9225 * The group is fully used and the tasks don't compete for more CPU
9226 * cycles. Nevertheless, some tasks might wait before running.
9227 */
9228 group_fully_busy,
9229 /*
9230 * One task doesn't fit with CPU's capacity and must be migrated to a
9231 * more powerful CPU.
9232 */
9233 group_misfit_task,
9234 /*
9235 * Balance SMT group that's fully busy. Can benefit from migration
9236 * a task on SMT with busy sibling to another CPU on idle core.
9237 */
9238 group_smt_balance,
9239 /*
9240 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9241 * and the task should be migrated to it instead of running on the
9242 * current CPU.
9243 */
9244 group_asym_packing,
9245 /*
9246 * The tasks' affinity constraints previously prevented the scheduler
9247 * from balancing the load across the system.
9248 */
9249 group_imbalanced,
9250 /*
9251 * The CPU is overloaded and can't provide expected CPU cycles to all
9252 * tasks.
9253 */
9254 group_overloaded
9255 };
9256
9257 enum migration_type {
9258 migrate_load = 0,
9259 migrate_util,
9260 migrate_task,
9261 migrate_misfit
9262 };
9263
9264 #define LBF_ALL_PINNED 0x01
9265 #define LBF_NEED_BREAK 0x02
9266 #define LBF_DST_PINNED 0x04
9267 #define LBF_SOME_PINNED 0x08
9268 #define LBF_ACTIVE_LB 0x10
9269
9270 struct lb_env {
9271 struct sched_domain *sd;
9272
9273 struct rq *src_rq;
9274 int src_cpu;
9275
9276 int dst_cpu;
9277 struct rq *dst_rq;
9278
9279 struct cpumask *dst_grpmask;
9280 int new_dst_cpu;
9281 enum cpu_idle_type idle;
9282 long imbalance;
9283 /* The set of CPUs under consideration for load-balancing */
9284 struct cpumask *cpus;
9285
9286 unsigned int flags;
9287
9288 unsigned int loop;
9289 unsigned int loop_break;
9290 unsigned int loop_max;
9291
9292 enum fbq_type fbq_type;
9293 enum migration_type migration_type;
9294 struct list_head tasks;
9295 };
9296
9297 /*
9298 * Is this task likely cache-hot:
9299 */
task_hot(struct task_struct * p,struct lb_env * env)9300 static int task_hot(struct task_struct *p, struct lb_env *env)
9301 {
9302 s64 delta;
9303
9304 lockdep_assert_rq_held(env->src_rq);
9305
9306 if (p->sched_class != &fair_sched_class)
9307 return 0;
9308
9309 if (unlikely(task_has_idle_policy(p)))
9310 return 0;
9311
9312 /* SMT siblings share cache */
9313 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9314 return 0;
9315
9316 /*
9317 * Buddy candidates are cache hot:
9318 */
9319 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9320 (&p->se == cfs_rq_of(&p->se)->next))
9321 return 1;
9322
9323 if (sysctl_sched_migration_cost == -1)
9324 return 1;
9325
9326 /*
9327 * Don't migrate task if the task's cookie does not match
9328 * with the destination CPU's core cookie.
9329 */
9330 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9331 return 1;
9332
9333 if (sysctl_sched_migration_cost == 0)
9334 return 0;
9335
9336 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9337
9338 return delta < (s64)sysctl_sched_migration_cost;
9339 }
9340
9341 #ifdef CONFIG_NUMA_BALANCING
9342 /*
9343 * Returns a positive value, if task migration degrades locality.
9344 * Returns 0, if task migration is not affected by locality.
9345 * Returns a negative value, if task migration improves locality i.e migration preferred.
9346 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9347 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9348 {
9349 struct numa_group *numa_group = rcu_dereference(p->numa_group);
9350 unsigned long src_weight, dst_weight;
9351 int src_nid, dst_nid, dist;
9352
9353 if (!static_branch_likely(&sched_numa_balancing))
9354 return 0;
9355
9356 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9357 return 0;
9358
9359 src_nid = cpu_to_node(env->src_cpu);
9360 dst_nid = cpu_to_node(env->dst_cpu);
9361
9362 if (src_nid == dst_nid)
9363 return 0;
9364
9365 /* Migrating away from the preferred node is always bad. */
9366 if (src_nid == p->numa_preferred_nid) {
9367 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9368 return 1;
9369 else
9370 return 0;
9371 }
9372
9373 /* Encourage migration to the preferred node. */
9374 if (dst_nid == p->numa_preferred_nid)
9375 return -1;
9376
9377 /* Leaving a core idle is often worse than degrading locality. */
9378 if (env->idle == CPU_IDLE)
9379 return 0;
9380
9381 dist = node_distance(src_nid, dst_nid);
9382 if (numa_group) {
9383 src_weight = group_weight(p, src_nid, dist);
9384 dst_weight = group_weight(p, dst_nid, dist);
9385 } else {
9386 src_weight = task_weight(p, src_nid, dist);
9387 dst_weight = task_weight(p, dst_nid, dist);
9388 }
9389
9390 return src_weight - dst_weight;
9391 }
9392
9393 #else /* !CONFIG_NUMA_BALANCING: */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9394 static inline long migrate_degrades_locality(struct task_struct *p,
9395 struct lb_env *env)
9396 {
9397 return 0;
9398 }
9399 #endif /* !CONFIG_NUMA_BALANCING */
9400
9401 /*
9402 * Check whether the task is ineligible on the destination cpu
9403 *
9404 * When the PLACE_LAG scheduling feature is enabled and
9405 * dst_cfs_rq->nr_queued is greater than 1, if the task
9406 * is ineligible, it will also be ineligible when
9407 * it is migrated to the destination cpu.
9408 */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)9409 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9410 {
9411 struct cfs_rq *dst_cfs_rq;
9412
9413 #ifdef CONFIG_FAIR_GROUP_SCHED
9414 dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9415 #else
9416 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9417 #endif
9418 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued &&
9419 !entity_eligible(task_cfs_rq(p), &p->se))
9420 return 1;
9421
9422 return 0;
9423 }
9424
9425 /*
9426 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9427 */
9428 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9429 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9430 {
9431 long degrades, hot;
9432
9433 lockdep_assert_rq_held(env->src_rq);
9434 if (p->sched_task_hot)
9435 p->sched_task_hot = 0;
9436
9437 /*
9438 * We do not migrate tasks that are:
9439 * 1) delayed dequeued unless we migrate load, or
9440 * 2) target cfs_rq is in throttled hierarchy, or
9441 * 3) cannot be migrated to this CPU due to cpus_ptr, or
9442 * 4) running (obviously), or
9443 * 5) are cache-hot on their current CPU, or
9444 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
9445 */
9446 if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
9447 return 0;
9448
9449 if (lb_throttled_hierarchy(p, env->dst_cpu))
9450 return 0;
9451
9452 /*
9453 * We want to prioritize the migration of eligible tasks.
9454 * For ineligible tasks we soft-limit them and only allow
9455 * them to migrate when nr_balance_failed is non-zero to
9456 * avoid load-balancing trying very hard to balance the load.
9457 */
9458 if (!env->sd->nr_balance_failed &&
9459 task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9460 return 0;
9461
9462 /* Disregard percpu kthreads; they are where they need to be. */
9463 if (kthread_is_per_cpu(p))
9464 return 0;
9465
9466 if (task_is_blocked(p))
9467 return 0;
9468
9469 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9470 int cpu;
9471
9472 schedstat_inc(p->stats.nr_failed_migrations_affine);
9473
9474 env->flags |= LBF_SOME_PINNED;
9475
9476 /*
9477 * Remember if this task can be migrated to any other CPU in
9478 * our sched_group. We may want to revisit it if we couldn't
9479 * meet load balance goals by pulling other tasks on src_cpu.
9480 *
9481 * Avoid computing new_dst_cpu
9482 * - for NEWLY_IDLE
9483 * - if we have already computed one in current iteration
9484 * - if it's an active balance
9485 */
9486 if (env->idle == CPU_NEWLY_IDLE ||
9487 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9488 return 0;
9489
9490 /* Prevent to re-select dst_cpu via env's CPUs: */
9491 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
9492
9493 if (cpu < nr_cpu_ids) {
9494 env->flags |= LBF_DST_PINNED;
9495 env->new_dst_cpu = cpu;
9496 }
9497
9498 return 0;
9499 }
9500
9501 /* Record that we found at least one task that could run on dst_cpu */
9502 env->flags &= ~LBF_ALL_PINNED;
9503
9504 if (task_on_cpu(env->src_rq, p) ||
9505 task_current_donor(env->src_rq, p)) {
9506 schedstat_inc(p->stats.nr_failed_migrations_running);
9507 return 0;
9508 }
9509
9510 /*
9511 * Aggressive migration if:
9512 * 1) active balance
9513 * 2) destination numa is preferred
9514 * 3) task is cache cold, or
9515 * 4) too many balance attempts have failed.
9516 */
9517 if (env->flags & LBF_ACTIVE_LB)
9518 return 1;
9519
9520 degrades = migrate_degrades_locality(p, env);
9521 if (!degrades)
9522 hot = task_hot(p, env);
9523 else
9524 hot = degrades > 0;
9525
9526 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9527 if (hot)
9528 p->sched_task_hot = 1;
9529 return 1;
9530 }
9531
9532 schedstat_inc(p->stats.nr_failed_migrations_hot);
9533 return 0;
9534 }
9535
9536 /*
9537 * detach_task() -- detach the task for the migration specified in env
9538 */
detach_task(struct task_struct * p,struct lb_env * env)9539 static void detach_task(struct task_struct *p, struct lb_env *env)
9540 {
9541 lockdep_assert_rq_held(env->src_rq);
9542
9543 if (p->sched_task_hot) {
9544 p->sched_task_hot = 0;
9545 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9546 schedstat_inc(p->stats.nr_forced_migrations);
9547 }
9548
9549 WARN_ON(task_current(env->src_rq, p));
9550 WARN_ON(task_current_donor(env->src_rq, p));
9551
9552 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9553 set_task_cpu(p, env->dst_cpu);
9554 }
9555
9556 /*
9557 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9558 * part of active balancing operations within "domain".
9559 *
9560 * Returns a task if successful and NULL otherwise.
9561 */
detach_one_task(struct lb_env * env)9562 static struct task_struct *detach_one_task(struct lb_env *env)
9563 {
9564 struct task_struct *p;
9565
9566 lockdep_assert_rq_held(env->src_rq);
9567
9568 list_for_each_entry_reverse(p,
9569 &env->src_rq->cfs_tasks, se.group_node) {
9570 if (!can_migrate_task(p, env))
9571 continue;
9572
9573 detach_task(p, env);
9574
9575 /*
9576 * Right now, this is only the second place where
9577 * lb_gained[env->idle] is updated (other is detach_tasks)
9578 * so we can safely collect stats here rather than
9579 * inside detach_tasks().
9580 */
9581 schedstat_inc(env->sd->lb_gained[env->idle]);
9582 return p;
9583 }
9584 return NULL;
9585 }
9586
9587 /*
9588 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9589 * busiest_rq, as part of a balancing operation within domain "sd".
9590 *
9591 * Returns number of detached tasks if successful and 0 otherwise.
9592 */
detach_tasks(struct lb_env * env)9593 static int detach_tasks(struct lb_env *env)
9594 {
9595 struct list_head *tasks = &env->src_rq->cfs_tasks;
9596 unsigned long util, load;
9597 struct task_struct *p;
9598 int detached = 0;
9599
9600 lockdep_assert_rq_held(env->src_rq);
9601
9602 /*
9603 * Source run queue has been emptied by another CPU, clear
9604 * LBF_ALL_PINNED flag as we will not test any task.
9605 */
9606 if (env->src_rq->nr_running <= 1) {
9607 env->flags &= ~LBF_ALL_PINNED;
9608 return 0;
9609 }
9610
9611 if (env->imbalance <= 0)
9612 return 0;
9613
9614 while (!list_empty(tasks)) {
9615 /*
9616 * We don't want to steal all, otherwise we may be treated likewise,
9617 * which could at worst lead to a livelock crash.
9618 */
9619 if (env->idle && env->src_rq->nr_running <= 1)
9620 break;
9621
9622 env->loop++;
9623 /* We've more or less seen every task there is, call it quits */
9624 if (env->loop > env->loop_max)
9625 break;
9626
9627 /* take a breather every nr_migrate tasks */
9628 if (env->loop > env->loop_break) {
9629 env->loop_break += SCHED_NR_MIGRATE_BREAK;
9630 env->flags |= LBF_NEED_BREAK;
9631 break;
9632 }
9633
9634 p = list_last_entry(tasks, struct task_struct, se.group_node);
9635
9636 if (!can_migrate_task(p, env))
9637 goto next;
9638
9639 switch (env->migration_type) {
9640 case migrate_load:
9641 /*
9642 * Depending of the number of CPUs and tasks and the
9643 * cgroup hierarchy, task_h_load() can return a null
9644 * value. Make sure that env->imbalance decreases
9645 * otherwise detach_tasks() will stop only after
9646 * detaching up to loop_max tasks.
9647 */
9648 load = max_t(unsigned long, task_h_load(p), 1);
9649
9650 if (sched_feat(LB_MIN) &&
9651 load < 16 && !env->sd->nr_balance_failed)
9652 goto next;
9653
9654 /*
9655 * Make sure that we don't migrate too much load.
9656 * Nevertheless, let relax the constraint if
9657 * scheduler fails to find a good waiting task to
9658 * migrate.
9659 */
9660 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9661 goto next;
9662
9663 env->imbalance -= load;
9664 break;
9665
9666 case migrate_util:
9667 util = task_util_est(p);
9668
9669 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9670 goto next;
9671
9672 env->imbalance -= util;
9673 break;
9674
9675 case migrate_task:
9676 env->imbalance--;
9677 break;
9678
9679 case migrate_misfit:
9680 /* This is not a misfit task */
9681 if (task_fits_cpu(p, env->src_cpu))
9682 goto next;
9683
9684 env->imbalance = 0;
9685 break;
9686 }
9687
9688 detach_task(p, env);
9689 list_add(&p->se.group_node, &env->tasks);
9690
9691 detached++;
9692
9693 #ifdef CONFIG_PREEMPTION
9694 /*
9695 * NEWIDLE balancing is a source of latency, so preemptible
9696 * kernels will stop after the first task is detached to minimize
9697 * the critical section.
9698 */
9699 if (env->idle == CPU_NEWLY_IDLE)
9700 break;
9701 #endif
9702
9703 /*
9704 * We only want to steal up to the prescribed amount of
9705 * load/util/tasks.
9706 */
9707 if (env->imbalance <= 0)
9708 break;
9709
9710 continue;
9711 next:
9712 if (p->sched_task_hot)
9713 schedstat_inc(p->stats.nr_failed_migrations_hot);
9714
9715 list_move(&p->se.group_node, tasks);
9716 }
9717
9718 /*
9719 * Right now, this is one of only two places we collect this stat
9720 * so we can safely collect detach_one_task() stats here rather
9721 * than inside detach_one_task().
9722 */
9723 schedstat_add(env->sd->lb_gained[env->idle], detached);
9724
9725 return detached;
9726 }
9727
9728 /*
9729 * attach_task() -- attach the task detached by detach_task() to its new rq.
9730 */
attach_task(struct rq * rq,struct task_struct * p)9731 static void attach_task(struct rq *rq, struct task_struct *p)
9732 {
9733 lockdep_assert_rq_held(rq);
9734
9735 WARN_ON_ONCE(task_rq(p) != rq);
9736 activate_task(rq, p, ENQUEUE_NOCLOCK);
9737 wakeup_preempt(rq, p, 0);
9738 }
9739
9740 /*
9741 * attach_one_task() -- attaches the task returned from detach_one_task() to
9742 * its new rq.
9743 */
attach_one_task(struct rq * rq,struct task_struct * p)9744 static void attach_one_task(struct rq *rq, struct task_struct *p)
9745 {
9746 struct rq_flags rf;
9747
9748 rq_lock(rq, &rf);
9749 update_rq_clock(rq);
9750 attach_task(rq, p);
9751 rq_unlock(rq, &rf);
9752 }
9753
9754 /*
9755 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9756 * new rq.
9757 */
attach_tasks(struct lb_env * env)9758 static void attach_tasks(struct lb_env *env)
9759 {
9760 struct list_head *tasks = &env->tasks;
9761 struct task_struct *p;
9762 struct rq_flags rf;
9763
9764 rq_lock(env->dst_rq, &rf);
9765 update_rq_clock(env->dst_rq);
9766
9767 while (!list_empty(tasks)) {
9768 p = list_first_entry(tasks, struct task_struct, se.group_node);
9769 list_del_init(&p->se.group_node);
9770
9771 attach_task(env->dst_rq, p);
9772 }
9773
9774 rq_unlock(env->dst_rq, &rf);
9775 }
9776
9777 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9778 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9779 {
9780 if (cfs_rq->avg.load_avg)
9781 return true;
9782
9783 if (cfs_rq->avg.util_avg)
9784 return true;
9785
9786 return false;
9787 }
9788
others_have_blocked(struct rq * rq)9789 static inline bool others_have_blocked(struct rq *rq)
9790 {
9791 if (cpu_util_rt(rq))
9792 return true;
9793
9794 if (cpu_util_dl(rq))
9795 return true;
9796
9797 if (hw_load_avg(rq))
9798 return true;
9799
9800 if (cpu_util_irq(rq))
9801 return true;
9802
9803 return false;
9804 }
9805
update_blocked_load_tick(struct rq * rq)9806 static inline void update_blocked_load_tick(struct rq *rq)
9807 {
9808 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9809 }
9810
update_blocked_load_status(struct rq * rq,bool has_blocked)9811 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9812 {
9813 if (!has_blocked)
9814 rq->has_blocked_load = 0;
9815 }
9816 #else /* !CONFIG_NO_HZ_COMMON: */
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9817 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)9818 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)9819 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)9820 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9821 #endif /* !CONFIG_NO_HZ_COMMON */
9822
__update_blocked_others(struct rq * rq,bool * done)9823 static bool __update_blocked_others(struct rq *rq, bool *done)
9824 {
9825 bool updated;
9826
9827 /*
9828 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9829 * DL and IRQ signals have been updated before updating CFS.
9830 */
9831 updated = update_other_load_avgs(rq);
9832
9833 if (others_have_blocked(rq))
9834 *done = false;
9835
9836 return updated;
9837 }
9838
9839 #ifdef CONFIG_FAIR_GROUP_SCHED
9840
__update_blocked_fair(struct rq * rq,bool * done)9841 static bool __update_blocked_fair(struct rq *rq, bool *done)
9842 {
9843 struct cfs_rq *cfs_rq, *pos;
9844 bool decayed = false;
9845 int cpu = cpu_of(rq);
9846
9847 /*
9848 * Iterates the task_group tree in a bottom up fashion, see
9849 * list_add_leaf_cfs_rq() for details.
9850 */
9851 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9852 struct sched_entity *se;
9853
9854 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9855 update_tg_load_avg(cfs_rq);
9856
9857 if (cfs_rq->nr_queued == 0)
9858 update_idle_cfs_rq_clock_pelt(cfs_rq);
9859
9860 if (cfs_rq == &rq->cfs)
9861 decayed = true;
9862 }
9863
9864 /* Propagate pending load changes to the parent, if any: */
9865 se = cfs_rq->tg->se[cpu];
9866 if (se && !skip_blocked_update(se))
9867 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9868
9869 /*
9870 * There can be a lot of idle CPU cgroups. Don't let fully
9871 * decayed cfs_rqs linger on the list.
9872 */
9873 if (cfs_rq_is_decayed(cfs_rq))
9874 list_del_leaf_cfs_rq(cfs_rq);
9875
9876 /* Don't need periodic decay once load/util_avg are null */
9877 if (cfs_rq_has_blocked(cfs_rq))
9878 *done = false;
9879 }
9880
9881 return decayed;
9882 }
9883
9884 /*
9885 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9886 * This needs to be done in a top-down fashion because the load of a child
9887 * group is a fraction of its parents load.
9888 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)9889 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9890 {
9891 struct rq *rq = rq_of(cfs_rq);
9892 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9893 unsigned long now = jiffies;
9894 unsigned long load;
9895
9896 if (cfs_rq->last_h_load_update == now)
9897 return;
9898
9899 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9900 for_each_sched_entity(se) {
9901 cfs_rq = cfs_rq_of(se);
9902 WRITE_ONCE(cfs_rq->h_load_next, se);
9903 if (cfs_rq->last_h_load_update == now)
9904 break;
9905 }
9906
9907 if (!se) {
9908 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9909 cfs_rq->last_h_load_update = now;
9910 }
9911
9912 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9913 load = cfs_rq->h_load;
9914 load = div64_ul(load * se->avg.load_avg,
9915 cfs_rq_load_avg(cfs_rq) + 1);
9916 cfs_rq = group_cfs_rq(se);
9917 cfs_rq->h_load = load;
9918 cfs_rq->last_h_load_update = now;
9919 }
9920 }
9921
task_h_load(struct task_struct * p)9922 static unsigned long task_h_load(struct task_struct *p)
9923 {
9924 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9925
9926 update_cfs_rq_h_load(cfs_rq);
9927 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9928 cfs_rq_load_avg(cfs_rq) + 1);
9929 }
9930 #else /* !CONFIG_FAIR_GROUP_SCHED: */
__update_blocked_fair(struct rq * rq,bool * done)9931 static bool __update_blocked_fair(struct rq *rq, bool *done)
9932 {
9933 struct cfs_rq *cfs_rq = &rq->cfs;
9934 bool decayed;
9935
9936 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9937 if (cfs_rq_has_blocked(cfs_rq))
9938 *done = false;
9939
9940 return decayed;
9941 }
9942
task_h_load(struct task_struct * p)9943 static unsigned long task_h_load(struct task_struct *p)
9944 {
9945 return p->se.avg.load_avg;
9946 }
9947 #endif /* !CONFIG_FAIR_GROUP_SCHED */
9948
sched_balance_update_blocked_averages(int cpu)9949 static void sched_balance_update_blocked_averages(int cpu)
9950 {
9951 bool decayed = false, done = true;
9952 struct rq *rq = cpu_rq(cpu);
9953 struct rq_flags rf;
9954
9955 rq_lock_irqsave(rq, &rf);
9956 update_blocked_load_tick(rq);
9957 update_rq_clock(rq);
9958
9959 decayed |= __update_blocked_others(rq, &done);
9960 decayed |= __update_blocked_fair(rq, &done);
9961
9962 update_blocked_load_status(rq, !done);
9963 if (decayed)
9964 cpufreq_update_util(rq, 0);
9965 rq_unlock_irqrestore(rq, &rf);
9966 }
9967
9968 /********** Helpers for sched_balance_find_src_group ************************/
9969
9970 /*
9971 * sg_lb_stats - stats of a sched_group required for load-balancing:
9972 */
9973 struct sg_lb_stats {
9974 unsigned long avg_load; /* Avg load over the CPUs of the group */
9975 unsigned long group_load; /* Total load over the CPUs of the group */
9976 unsigned long group_capacity; /* Capacity over the CPUs of the group */
9977 unsigned long group_util; /* Total utilization over the CPUs of the group */
9978 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9979 unsigned int sum_nr_running; /* Nr of all tasks running in the group */
9980 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9981 unsigned int idle_cpus; /* Nr of idle CPUs in the group */
9982 unsigned int group_weight;
9983 enum group_type group_type;
9984 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9985 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9986 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9987 #ifdef CONFIG_NUMA_BALANCING
9988 unsigned int nr_numa_running;
9989 unsigned int nr_preferred_running;
9990 #endif
9991 };
9992
9993 /*
9994 * sd_lb_stats - stats of a sched_domain required for load-balancing:
9995 */
9996 struct sd_lb_stats {
9997 struct sched_group *busiest; /* Busiest group in this sd */
9998 struct sched_group *local; /* Local group in this sd */
9999 unsigned long total_load; /* Total load of all groups in sd */
10000 unsigned long total_capacity; /* Total capacity of all groups in sd */
10001 unsigned long avg_load; /* Average load across all groups in sd */
10002 unsigned int prefer_sibling; /* Tasks should go to sibling first */
10003
10004 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */
10005 struct sg_lb_stats local_stat; /* Statistics of the local group */
10006 };
10007
init_sd_lb_stats(struct sd_lb_stats * sds)10008 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
10009 {
10010 /*
10011 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
10012 * local_stat because update_sg_lb_stats() does a full clear/assignment.
10013 * We must however set busiest_stat::group_type and
10014 * busiest_stat::idle_cpus to the worst busiest group because
10015 * update_sd_pick_busiest() reads these before assignment.
10016 */
10017 *sds = (struct sd_lb_stats){
10018 .busiest = NULL,
10019 .local = NULL,
10020 .total_load = 0UL,
10021 .total_capacity = 0UL,
10022 .busiest_stat = {
10023 .idle_cpus = UINT_MAX,
10024 .group_type = group_has_spare,
10025 },
10026 };
10027 }
10028
scale_rt_capacity(int cpu)10029 static unsigned long scale_rt_capacity(int cpu)
10030 {
10031 unsigned long max = get_actual_cpu_capacity(cpu);
10032 struct rq *rq = cpu_rq(cpu);
10033 unsigned long used, free;
10034 unsigned long irq;
10035
10036 irq = cpu_util_irq(rq);
10037
10038 if (unlikely(irq >= max))
10039 return 1;
10040
10041 /*
10042 * avg_rt.util_avg and avg_dl.util_avg track binary signals
10043 * (running and not running) with weights 0 and 1024 respectively.
10044 */
10045 used = cpu_util_rt(rq);
10046 used += cpu_util_dl(rq);
10047
10048 if (unlikely(used >= max))
10049 return 1;
10050
10051 free = max - used;
10052
10053 return scale_irq_capacity(free, irq, max);
10054 }
10055
update_cpu_capacity(struct sched_domain * sd,int cpu)10056 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
10057 {
10058 unsigned long capacity = scale_rt_capacity(cpu);
10059 struct sched_group *sdg = sd->groups;
10060
10061 if (!capacity)
10062 capacity = 1;
10063
10064 cpu_rq(cpu)->cpu_capacity = capacity;
10065 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
10066
10067 sdg->sgc->capacity = capacity;
10068 sdg->sgc->min_capacity = capacity;
10069 sdg->sgc->max_capacity = capacity;
10070 }
10071
update_group_capacity(struct sched_domain * sd,int cpu)10072 void update_group_capacity(struct sched_domain *sd, int cpu)
10073 {
10074 struct sched_domain *child = sd->child;
10075 struct sched_group *group, *sdg = sd->groups;
10076 unsigned long capacity, min_capacity, max_capacity;
10077 unsigned long interval;
10078
10079 interval = msecs_to_jiffies(sd->balance_interval);
10080 interval = clamp(interval, 1UL, max_load_balance_interval);
10081 sdg->sgc->next_update = jiffies + interval;
10082
10083 if (!child) {
10084 update_cpu_capacity(sd, cpu);
10085 return;
10086 }
10087
10088 capacity = 0;
10089 min_capacity = ULONG_MAX;
10090 max_capacity = 0;
10091
10092 if (child->flags & SD_NUMA) {
10093 /*
10094 * SD_NUMA domains cannot assume that child groups
10095 * span the current group.
10096 */
10097
10098 for_each_cpu(cpu, sched_group_span(sdg)) {
10099 unsigned long cpu_cap = capacity_of(cpu);
10100
10101 capacity += cpu_cap;
10102 min_capacity = min(cpu_cap, min_capacity);
10103 max_capacity = max(cpu_cap, max_capacity);
10104 }
10105 } else {
10106 /*
10107 * !SD_NUMA domains can assume that child groups
10108 * span the current group.
10109 */
10110
10111 group = child->groups;
10112 do {
10113 struct sched_group_capacity *sgc = group->sgc;
10114
10115 capacity += sgc->capacity;
10116 min_capacity = min(sgc->min_capacity, min_capacity);
10117 max_capacity = max(sgc->max_capacity, max_capacity);
10118 group = group->next;
10119 } while (group != child->groups);
10120 }
10121
10122 sdg->sgc->capacity = capacity;
10123 sdg->sgc->min_capacity = min_capacity;
10124 sdg->sgc->max_capacity = max_capacity;
10125 }
10126
10127 /*
10128 * Check whether the capacity of the rq has been noticeably reduced by side
10129 * activity. The imbalance_pct is used for the threshold.
10130 * Return true is the capacity is reduced
10131 */
10132 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)10133 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10134 {
10135 return ((rq->cpu_capacity * sd->imbalance_pct) <
10136 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10137 }
10138
10139 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)10140 static inline bool check_misfit_status(struct rq *rq)
10141 {
10142 return rq->misfit_task_load;
10143 }
10144
10145 /*
10146 * Group imbalance indicates (and tries to solve) the problem where balancing
10147 * groups is inadequate due to ->cpus_ptr constraints.
10148 *
10149 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10150 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10151 * Something like:
10152 *
10153 * { 0 1 2 3 } { 4 5 6 7 }
10154 * * * * *
10155 *
10156 * If we were to balance group-wise we'd place two tasks in the first group and
10157 * two tasks in the second group. Clearly this is undesired as it will overload
10158 * cpu 3 and leave one of the CPUs in the second group unused.
10159 *
10160 * The current solution to this issue is detecting the skew in the first group
10161 * by noticing the lower domain failed to reach balance and had difficulty
10162 * moving tasks due to affinity constraints.
10163 *
10164 * When this is so detected; this group becomes a candidate for busiest; see
10165 * update_sd_pick_busiest(). And calculate_imbalance() and
10166 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10167 * to create an effective group imbalance.
10168 *
10169 * This is a somewhat tricky proposition since the next run might not find the
10170 * group imbalance and decide the groups need to be balanced again. A most
10171 * subtle and fragile situation.
10172 */
10173
sg_imbalanced(struct sched_group * group)10174 static inline int sg_imbalanced(struct sched_group *group)
10175 {
10176 return group->sgc->imbalance;
10177 }
10178
10179 /*
10180 * group_has_capacity returns true if the group has spare capacity that could
10181 * be used by some tasks.
10182 * We consider that a group has spare capacity if the number of task is
10183 * smaller than the number of CPUs or if the utilization is lower than the
10184 * available capacity for CFS tasks.
10185 * For the latter, we use a threshold to stabilize the state, to take into
10186 * account the variance of the tasks' load and to return true if the available
10187 * capacity in meaningful for the load balancer.
10188 * As an example, an available capacity of 1% can appear but it doesn't make
10189 * any benefit for the load balance.
10190 */
10191 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10192 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10193 {
10194 if (sgs->sum_nr_running < sgs->group_weight)
10195 return true;
10196
10197 if ((sgs->group_capacity * imbalance_pct) <
10198 (sgs->group_runnable * 100))
10199 return false;
10200
10201 if ((sgs->group_capacity * 100) >
10202 (sgs->group_util * imbalance_pct))
10203 return true;
10204
10205 return false;
10206 }
10207
10208 /*
10209 * group_is_overloaded returns true if the group has more tasks than it can
10210 * handle.
10211 * group_is_overloaded is not equals to !group_has_capacity because a group
10212 * with the exact right number of tasks, has no more spare capacity but is not
10213 * overloaded so both group_has_capacity and group_is_overloaded return
10214 * false.
10215 */
10216 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10217 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10218 {
10219 if (sgs->sum_nr_running <= sgs->group_weight)
10220 return false;
10221
10222 if ((sgs->group_capacity * 100) <
10223 (sgs->group_util * imbalance_pct))
10224 return true;
10225
10226 if ((sgs->group_capacity * imbalance_pct) <
10227 (sgs->group_runnable * 100))
10228 return true;
10229
10230 return false;
10231 }
10232
10233 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10234 group_type group_classify(unsigned int imbalance_pct,
10235 struct sched_group *group,
10236 struct sg_lb_stats *sgs)
10237 {
10238 if (group_is_overloaded(imbalance_pct, sgs))
10239 return group_overloaded;
10240
10241 if (sg_imbalanced(group))
10242 return group_imbalanced;
10243
10244 if (sgs->group_asym_packing)
10245 return group_asym_packing;
10246
10247 if (sgs->group_smt_balance)
10248 return group_smt_balance;
10249
10250 if (sgs->group_misfit_task_load)
10251 return group_misfit_task;
10252
10253 if (!group_has_capacity(imbalance_pct, sgs))
10254 return group_fully_busy;
10255
10256 return group_has_spare;
10257 }
10258
10259 /**
10260 * sched_use_asym_prio - Check whether asym_packing priority must be used
10261 * @sd: The scheduling domain of the load balancing
10262 * @cpu: A CPU
10263 *
10264 * Always use CPU priority when balancing load between SMT siblings. When
10265 * balancing load between cores, it is not sufficient that @cpu is idle. Only
10266 * use CPU priority if the whole core is idle.
10267 *
10268 * Returns: True if the priority of @cpu must be followed. False otherwise.
10269 */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10270 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10271 {
10272 if (!(sd->flags & SD_ASYM_PACKING))
10273 return false;
10274
10275 if (!sched_smt_active())
10276 return true;
10277
10278 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10279 }
10280
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)10281 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10282 {
10283 /*
10284 * First check if @dst_cpu can do asym_packing load balance. Only do it
10285 * if it has higher priority than @src_cpu.
10286 */
10287 return sched_use_asym_prio(sd, dst_cpu) &&
10288 sched_asym_prefer(dst_cpu, src_cpu);
10289 }
10290
10291 /**
10292 * sched_group_asym - Check if the destination CPU can do asym_packing balance
10293 * @env: The load balancing environment
10294 * @sgs: Load-balancing statistics of the candidate busiest group
10295 * @group: The candidate busiest group
10296 *
10297 * @env::dst_cpu can do asym_packing if it has higher priority than the
10298 * preferred CPU of @group.
10299 *
10300 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10301 * otherwise.
10302 */
10303 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10304 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10305 {
10306 /*
10307 * CPU priorities do not make sense for SMT cores with more than one
10308 * busy sibling.
10309 */
10310 if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10311 (sgs->group_weight - sgs->idle_cpus != 1))
10312 return false;
10313
10314 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
10315 }
10316
10317 /* 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)10318 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10319 struct sched_group *sg2)
10320 {
10321 if (!sg1 || !sg2)
10322 return false;
10323
10324 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10325 (sg2->flags & SD_SHARE_CPUCAPACITY);
10326 }
10327
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10328 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10329 struct sched_group *group)
10330 {
10331 if (!env->idle)
10332 return false;
10333
10334 /*
10335 * For SMT source group, it is better to move a task
10336 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10337 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10338 * will not be on.
10339 */
10340 if (group->flags & SD_SHARE_CPUCAPACITY &&
10341 sgs->sum_h_nr_running > 1)
10342 return true;
10343
10344 return false;
10345 }
10346
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10347 static inline long sibling_imbalance(struct lb_env *env,
10348 struct sd_lb_stats *sds,
10349 struct sg_lb_stats *busiest,
10350 struct sg_lb_stats *local)
10351 {
10352 int ncores_busiest, ncores_local;
10353 long imbalance;
10354
10355 if (!env->idle || !busiest->sum_nr_running)
10356 return 0;
10357
10358 ncores_busiest = sds->busiest->cores;
10359 ncores_local = sds->local->cores;
10360
10361 if (ncores_busiest == ncores_local) {
10362 imbalance = busiest->sum_nr_running;
10363 lsub_positive(&imbalance, local->sum_nr_running);
10364 return imbalance;
10365 }
10366
10367 /* Balance such that nr_running/ncores ratio are same on both groups */
10368 imbalance = ncores_local * busiest->sum_nr_running;
10369 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10370 /* Normalize imbalance and do rounding on normalization */
10371 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10372 imbalance /= ncores_local + ncores_busiest;
10373
10374 /* Take advantage of resource in an empty sched group */
10375 if (imbalance <= 1 && local->sum_nr_running == 0 &&
10376 busiest->sum_nr_running > 1)
10377 imbalance = 2;
10378
10379 return imbalance;
10380 }
10381
10382 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10383 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10384 {
10385 /*
10386 * When there is more than 1 task, the group_overloaded case already
10387 * takes care of cpu with reduced capacity
10388 */
10389 if (rq->cfs.h_nr_runnable != 1)
10390 return false;
10391
10392 return check_cpu_capacity(rq, sd);
10393 }
10394
10395 /**
10396 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10397 * @env: The load balancing environment.
10398 * @sds: Load-balancing data with statistics of the local group.
10399 * @group: sched_group whose statistics are to be updated.
10400 * @sgs: variable to hold the statistics for this group.
10401 * @sg_overloaded: sched_group is overloaded
10402 * @sg_overutilized: sched_group is overutilized
10403 */
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)10404 static inline void update_sg_lb_stats(struct lb_env *env,
10405 struct sd_lb_stats *sds,
10406 struct sched_group *group,
10407 struct sg_lb_stats *sgs,
10408 bool *sg_overloaded,
10409 bool *sg_overutilized)
10410 {
10411 int i, nr_running, local_group, sd_flags = env->sd->flags;
10412 bool balancing_at_rd = !env->sd->parent;
10413
10414 memset(sgs, 0, sizeof(*sgs));
10415
10416 local_group = group == sds->local;
10417
10418 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10419 struct rq *rq = cpu_rq(i);
10420 unsigned long load = cpu_load(rq);
10421
10422 sgs->group_load += load;
10423 sgs->group_util += cpu_util_cfs(i);
10424 sgs->group_runnable += cpu_runnable(rq);
10425 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
10426
10427 nr_running = rq->nr_running;
10428 sgs->sum_nr_running += nr_running;
10429
10430 if (cpu_overutilized(i))
10431 *sg_overutilized = 1;
10432
10433 /*
10434 * No need to call idle_cpu() if nr_running is not 0
10435 */
10436 if (!nr_running && idle_cpu(i)) {
10437 sgs->idle_cpus++;
10438 /* Idle cpu can't have misfit task */
10439 continue;
10440 }
10441
10442 /* Overload indicator is only updated at root domain */
10443 if (balancing_at_rd && nr_running > 1)
10444 *sg_overloaded = 1;
10445
10446 #ifdef CONFIG_NUMA_BALANCING
10447 /* Only fbq_classify_group() uses this to classify NUMA groups */
10448 if (sd_flags & SD_NUMA) {
10449 sgs->nr_numa_running += rq->nr_numa_running;
10450 sgs->nr_preferred_running += rq->nr_preferred_running;
10451 }
10452 #endif
10453 if (local_group)
10454 continue;
10455
10456 if (sd_flags & SD_ASYM_CPUCAPACITY) {
10457 /* Check for a misfit task on the cpu */
10458 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10459 sgs->group_misfit_task_load = rq->misfit_task_load;
10460 *sg_overloaded = 1;
10461 }
10462 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10463 /* Check for a task running on a CPU with reduced capacity */
10464 if (sgs->group_misfit_task_load < load)
10465 sgs->group_misfit_task_load = load;
10466 }
10467 }
10468
10469 sgs->group_capacity = group->sgc->capacity;
10470
10471 sgs->group_weight = group->group_weight;
10472
10473 /* Check if dst CPU is idle and preferred to this group */
10474 if (!local_group && env->idle && sgs->sum_h_nr_running &&
10475 sched_group_asym(env, sgs, group))
10476 sgs->group_asym_packing = 1;
10477
10478 /* Check for loaded SMT group to be balanced to dst CPU */
10479 if (!local_group && smt_balance(env, sgs, group))
10480 sgs->group_smt_balance = 1;
10481
10482 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10483
10484 /* Computing avg_load makes sense only when group is overloaded */
10485 if (sgs->group_type == group_overloaded)
10486 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10487 sgs->group_capacity;
10488 }
10489
10490 /**
10491 * update_sd_pick_busiest - return 1 on busiest group
10492 * @env: The load balancing environment.
10493 * @sds: sched_domain statistics
10494 * @sg: sched_group candidate to be checked for being the busiest
10495 * @sgs: sched_group statistics
10496 *
10497 * Determine if @sg is a busier group than the previously selected
10498 * busiest group.
10499 *
10500 * Return: %true if @sg is a busier group than the previously selected
10501 * busiest group. %false otherwise.
10502 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10503 static bool update_sd_pick_busiest(struct lb_env *env,
10504 struct sd_lb_stats *sds,
10505 struct sched_group *sg,
10506 struct sg_lb_stats *sgs)
10507 {
10508 struct sg_lb_stats *busiest = &sds->busiest_stat;
10509
10510 /* Make sure that there is at least one task to pull */
10511 if (!sgs->sum_h_nr_running)
10512 return false;
10513
10514 /*
10515 * Don't try to pull misfit tasks we can't help.
10516 * We can use max_capacity here as reduction in capacity on some
10517 * CPUs in the group should either be possible to resolve
10518 * internally or be covered by avg_load imbalance (eventually).
10519 */
10520 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10521 (sgs->group_type == group_misfit_task) &&
10522 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10523 sds->local_stat.group_type != group_has_spare))
10524 return false;
10525
10526 if (sgs->group_type > busiest->group_type)
10527 return true;
10528
10529 if (sgs->group_type < busiest->group_type)
10530 return false;
10531
10532 /*
10533 * The candidate and the current busiest group are the same type of
10534 * group. Let check which one is the busiest according to the type.
10535 */
10536
10537 switch (sgs->group_type) {
10538 case group_overloaded:
10539 /* Select the overloaded group with highest avg_load. */
10540 return sgs->avg_load > busiest->avg_load;
10541
10542 case group_imbalanced:
10543 /*
10544 * Select the 1st imbalanced group as we don't have any way to
10545 * choose one more than another.
10546 */
10547 return false;
10548
10549 case group_asym_packing:
10550 /* Prefer to move from lowest priority CPU's work */
10551 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
10552 READ_ONCE(sg->asym_prefer_cpu));
10553
10554 case group_misfit_task:
10555 /*
10556 * If we have more than one misfit sg go with the biggest
10557 * misfit.
10558 */
10559 return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10560
10561 case group_smt_balance:
10562 /*
10563 * Check if we have spare CPUs on either SMT group to
10564 * choose has spare or fully busy handling.
10565 */
10566 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10567 goto has_spare;
10568
10569 fallthrough;
10570
10571 case group_fully_busy:
10572 /*
10573 * Select the fully busy group with highest avg_load. In
10574 * theory, there is no need to pull task from such kind of
10575 * group because tasks have all compute capacity that they need
10576 * but we can still improve the overall throughput by reducing
10577 * contention when accessing shared HW resources.
10578 *
10579 * XXX for now avg_load is not computed and always 0 so we
10580 * select the 1st one, except if @sg is composed of SMT
10581 * siblings.
10582 */
10583
10584 if (sgs->avg_load < busiest->avg_load)
10585 return false;
10586
10587 if (sgs->avg_load == busiest->avg_load) {
10588 /*
10589 * SMT sched groups need more help than non-SMT groups.
10590 * If @sg happens to also be SMT, either choice is good.
10591 */
10592 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10593 return false;
10594 }
10595
10596 break;
10597
10598 case group_has_spare:
10599 /*
10600 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10601 * as we do not want to pull task off SMT core with one task
10602 * and make the core idle.
10603 */
10604 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10605 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10606 return false;
10607 else
10608 return true;
10609 }
10610 has_spare:
10611
10612 /*
10613 * Select not overloaded group with lowest number of idle CPUs
10614 * and highest number of running tasks. We could also compare
10615 * the spare capacity which is more stable but it can end up
10616 * that the group has less spare capacity but finally more idle
10617 * CPUs which means less opportunity to pull tasks.
10618 */
10619 if (sgs->idle_cpus > busiest->idle_cpus)
10620 return false;
10621 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10622 (sgs->sum_nr_running <= busiest->sum_nr_running))
10623 return false;
10624
10625 break;
10626 }
10627
10628 /*
10629 * Candidate sg has no more than one task per CPU and has higher
10630 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10631 * throughput. Maximize throughput, power/energy consequences are not
10632 * considered.
10633 */
10634 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10635 (sgs->group_type <= group_fully_busy) &&
10636 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10637 return false;
10638
10639 return true;
10640 }
10641
10642 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10643 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10644 {
10645 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10646 return regular;
10647 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10648 return remote;
10649 return all;
10650 }
10651
fbq_classify_rq(struct rq * rq)10652 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10653 {
10654 if (rq->nr_running > rq->nr_numa_running)
10655 return regular;
10656 if (rq->nr_running > rq->nr_preferred_running)
10657 return remote;
10658 return all;
10659 }
10660 #else /* !CONFIG_NUMA_BALANCING: */
fbq_classify_group(struct sg_lb_stats * sgs)10661 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10662 {
10663 return all;
10664 }
10665
fbq_classify_rq(struct rq * rq)10666 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10667 {
10668 return regular;
10669 }
10670 #endif /* !CONFIG_NUMA_BALANCING */
10671
10672
10673 struct sg_lb_stats;
10674
10675 /*
10676 * task_running_on_cpu - return 1 if @p is running on @cpu.
10677 */
10678
task_running_on_cpu(int cpu,struct task_struct * p)10679 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10680 {
10681 /* Task has no contribution or is new */
10682 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10683 return 0;
10684
10685 if (task_on_rq_queued(p))
10686 return 1;
10687
10688 return 0;
10689 }
10690
10691 /**
10692 * idle_cpu_without - would a given CPU be idle without p ?
10693 * @cpu: the processor on which idleness is tested.
10694 * @p: task which should be ignored.
10695 *
10696 * Return: 1 if the CPU would be idle. 0 otherwise.
10697 */
idle_cpu_without(int cpu,struct task_struct * p)10698 static int idle_cpu_without(int cpu, struct task_struct *p)
10699 {
10700 struct rq *rq = cpu_rq(cpu);
10701
10702 if (rq->curr != rq->idle && rq->curr != p)
10703 return 0;
10704
10705 /*
10706 * rq->nr_running can't be used but an updated version without the
10707 * impact of p on cpu must be used instead. The updated nr_running
10708 * be computed and tested before calling idle_cpu_without().
10709 */
10710
10711 if (rq->ttwu_pending)
10712 return 0;
10713
10714 return 1;
10715 }
10716
10717 /*
10718 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10719 * @sd: The sched_domain level to look for idlest group.
10720 * @group: sched_group whose statistics are to be updated.
10721 * @sgs: variable to hold the statistics for this group.
10722 * @p: The task for which we look for the idlest group/CPU.
10723 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10724 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10725 struct sched_group *group,
10726 struct sg_lb_stats *sgs,
10727 struct task_struct *p)
10728 {
10729 int i, nr_running;
10730
10731 memset(sgs, 0, sizeof(*sgs));
10732
10733 /* Assume that task can't fit any CPU of the group */
10734 if (sd->flags & SD_ASYM_CPUCAPACITY)
10735 sgs->group_misfit_task_load = 1;
10736
10737 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
10738 struct rq *rq = cpu_rq(i);
10739 unsigned int local;
10740
10741 sgs->group_load += cpu_load_without(rq, p);
10742 sgs->group_util += cpu_util_without(i, p);
10743 sgs->group_runnable += cpu_runnable_without(rq, p);
10744 local = task_running_on_cpu(i, p);
10745 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
10746
10747 nr_running = rq->nr_running - local;
10748 sgs->sum_nr_running += nr_running;
10749
10750 /*
10751 * No need to call idle_cpu_without() if nr_running is not 0
10752 */
10753 if (!nr_running && idle_cpu_without(i, p))
10754 sgs->idle_cpus++;
10755
10756 /* Check if task fits in the CPU */
10757 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10758 sgs->group_misfit_task_load &&
10759 task_fits_cpu(p, i))
10760 sgs->group_misfit_task_load = 0;
10761
10762 }
10763
10764 sgs->group_capacity = group->sgc->capacity;
10765
10766 sgs->group_weight = group->group_weight;
10767
10768 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10769
10770 /*
10771 * Computing avg_load makes sense only when group is fully busy or
10772 * overloaded
10773 */
10774 if (sgs->group_type == group_fully_busy ||
10775 sgs->group_type == group_overloaded)
10776 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10777 sgs->group_capacity;
10778 }
10779
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10780 static bool update_pick_idlest(struct sched_group *idlest,
10781 struct sg_lb_stats *idlest_sgs,
10782 struct sched_group *group,
10783 struct sg_lb_stats *sgs)
10784 {
10785 if (sgs->group_type < idlest_sgs->group_type)
10786 return true;
10787
10788 if (sgs->group_type > idlest_sgs->group_type)
10789 return false;
10790
10791 /*
10792 * The candidate and the current idlest group are the same type of
10793 * group. Let check which one is the idlest according to the type.
10794 */
10795
10796 switch (sgs->group_type) {
10797 case group_overloaded:
10798 case group_fully_busy:
10799 /* Select the group with lowest avg_load. */
10800 if (idlest_sgs->avg_load <= sgs->avg_load)
10801 return false;
10802 break;
10803
10804 case group_imbalanced:
10805 case group_asym_packing:
10806 case group_smt_balance:
10807 /* Those types are not used in the slow wakeup path */
10808 return false;
10809
10810 case group_misfit_task:
10811 /* Select group with the highest max capacity */
10812 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10813 return false;
10814 break;
10815
10816 case group_has_spare:
10817 /* Select group with most idle CPUs */
10818 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10819 return false;
10820
10821 /* Select group with lowest group_util */
10822 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10823 idlest_sgs->group_util <= sgs->group_util)
10824 return false;
10825
10826 break;
10827 }
10828
10829 return true;
10830 }
10831
10832 /*
10833 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
10834 * domain.
10835 *
10836 * Assumes p is allowed on at least one CPU in sd.
10837 */
10838 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)10839 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10840 {
10841 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10842 struct sg_lb_stats local_sgs, tmp_sgs;
10843 struct sg_lb_stats *sgs;
10844 unsigned long imbalance;
10845 struct sg_lb_stats idlest_sgs = {
10846 .avg_load = UINT_MAX,
10847 .group_type = group_overloaded,
10848 };
10849
10850 do {
10851 int local_group;
10852
10853 /* Skip over this group if it has no CPUs allowed */
10854 if (!cpumask_intersects(sched_group_span(group),
10855 p->cpus_ptr))
10856 continue;
10857
10858 /* Skip over this group if no cookie matched */
10859 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10860 continue;
10861
10862 local_group = cpumask_test_cpu(this_cpu,
10863 sched_group_span(group));
10864
10865 if (local_group) {
10866 sgs = &local_sgs;
10867 local = group;
10868 } else {
10869 sgs = &tmp_sgs;
10870 }
10871
10872 update_sg_wakeup_stats(sd, group, sgs, p);
10873
10874 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10875 idlest = group;
10876 idlest_sgs = *sgs;
10877 }
10878
10879 } while (group = group->next, group != sd->groups);
10880
10881
10882 /* There is no idlest group to push tasks to */
10883 if (!idlest)
10884 return NULL;
10885
10886 /* The local group has been skipped because of CPU affinity */
10887 if (!local)
10888 return idlest;
10889
10890 /*
10891 * If the local group is idler than the selected idlest group
10892 * don't try and push the task.
10893 */
10894 if (local_sgs.group_type < idlest_sgs.group_type)
10895 return NULL;
10896
10897 /*
10898 * If the local group is busier than the selected idlest group
10899 * try and push the task.
10900 */
10901 if (local_sgs.group_type > idlest_sgs.group_type)
10902 return idlest;
10903
10904 switch (local_sgs.group_type) {
10905 case group_overloaded:
10906 case group_fully_busy:
10907
10908 /* Calculate allowed imbalance based on load */
10909 imbalance = scale_load_down(NICE_0_LOAD) *
10910 (sd->imbalance_pct-100) / 100;
10911
10912 /*
10913 * When comparing groups across NUMA domains, it's possible for
10914 * the local domain to be very lightly loaded relative to the
10915 * remote domains but "imbalance" skews the comparison making
10916 * remote CPUs look much more favourable. When considering
10917 * cross-domain, add imbalance to the load on the remote node
10918 * and consider staying local.
10919 */
10920
10921 if ((sd->flags & SD_NUMA) &&
10922 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10923 return NULL;
10924
10925 /*
10926 * If the local group is less loaded than the selected
10927 * idlest group don't try and push any tasks.
10928 */
10929 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10930 return NULL;
10931
10932 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10933 return NULL;
10934 break;
10935
10936 case group_imbalanced:
10937 case group_asym_packing:
10938 case group_smt_balance:
10939 /* Those type are not used in the slow wakeup path */
10940 return NULL;
10941
10942 case group_misfit_task:
10943 /* Select group with the highest max capacity */
10944 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10945 return NULL;
10946 break;
10947
10948 case group_has_spare:
10949 #ifdef CONFIG_NUMA
10950 if (sd->flags & SD_NUMA) {
10951 int imb_numa_nr = sd->imb_numa_nr;
10952 #ifdef CONFIG_NUMA_BALANCING
10953 int idlest_cpu;
10954 /*
10955 * If there is spare capacity at NUMA, try to select
10956 * the preferred node
10957 */
10958 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10959 return NULL;
10960
10961 idlest_cpu = cpumask_first(sched_group_span(idlest));
10962 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10963 return idlest;
10964 #endif /* CONFIG_NUMA_BALANCING */
10965 /*
10966 * Otherwise, keep the task close to the wakeup source
10967 * and improve locality if the number of running tasks
10968 * would remain below threshold where an imbalance is
10969 * allowed while accounting for the possibility the
10970 * task is pinned to a subset of CPUs. If there is a
10971 * real need of migration, periodic load balance will
10972 * take care of it.
10973 */
10974 if (p->nr_cpus_allowed != NR_CPUS) {
10975 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10976
10977 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10978 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10979 }
10980
10981 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10982 if (!adjust_numa_imbalance(imbalance,
10983 local_sgs.sum_nr_running + 1,
10984 imb_numa_nr)) {
10985 return NULL;
10986 }
10987 }
10988 #endif /* CONFIG_NUMA */
10989
10990 /*
10991 * Select group with highest number of idle CPUs. We could also
10992 * compare the utilization which is more stable but it can end
10993 * up that the group has less spare capacity but finally more
10994 * idle CPUs which means more opportunity to run task.
10995 */
10996 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10997 return NULL;
10998 break;
10999 }
11000
11001 return idlest;
11002 }
11003
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)11004 static void update_idle_cpu_scan(struct lb_env *env,
11005 unsigned long sum_util)
11006 {
11007 struct sched_domain_shared *sd_share;
11008 int llc_weight, pct;
11009 u64 x, y, tmp;
11010 /*
11011 * Update the number of CPUs to scan in LLC domain, which could
11012 * be used as a hint in select_idle_cpu(). The update of sd_share
11013 * could be expensive because it is within a shared cache line.
11014 * So the write of this hint only occurs during periodic load
11015 * balancing, rather than CPU_NEWLY_IDLE, because the latter
11016 * can fire way more frequently than the former.
11017 */
11018 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
11019 return;
11020
11021 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
11022 if (env->sd->span_weight != llc_weight)
11023 return;
11024
11025 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
11026 if (!sd_share)
11027 return;
11028
11029 /*
11030 * The number of CPUs to search drops as sum_util increases, when
11031 * sum_util hits 85% or above, the scan stops.
11032 * The reason to choose 85% as the threshold is because this is the
11033 * imbalance_pct(117) when a LLC sched group is overloaded.
11034 *
11035 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
11036 * and y'= y / SCHED_CAPACITY_SCALE
11037 *
11038 * x is the ratio of sum_util compared to the CPU capacity:
11039 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
11040 * y' is the ratio of CPUs to be scanned in the LLC domain,
11041 * and the number of CPUs to scan is calculated by:
11042 *
11043 * nr_scan = llc_weight * y' [2]
11044 *
11045 * When x hits the threshold of overloaded, AKA, when
11046 * x = 100 / pct, y drops to 0. According to [1],
11047 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
11048 *
11049 * Scale x by SCHED_CAPACITY_SCALE:
11050 * x' = sum_util / llc_weight; [3]
11051 *
11052 * and finally [1] becomes:
11053 * y = SCHED_CAPACITY_SCALE -
11054 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
11055 *
11056 */
11057 /* equation [3] */
11058 x = sum_util;
11059 do_div(x, llc_weight);
11060
11061 /* equation [4] */
11062 pct = env->sd->imbalance_pct;
11063 tmp = x * x * pct * pct;
11064 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
11065 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
11066 y = SCHED_CAPACITY_SCALE - tmp;
11067
11068 /* equation [2] */
11069 y *= llc_weight;
11070 do_div(y, SCHED_CAPACITY_SCALE);
11071 if ((int)y != sd_share->nr_idle_scan)
11072 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
11073 }
11074
11075 /**
11076 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11077 * @env: The load balancing environment.
11078 * @sds: variable to hold the statistics for this sched_domain.
11079 */
11080
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)11081 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11082 {
11083 struct sched_group *sg = env->sd->groups;
11084 struct sg_lb_stats *local = &sds->local_stat;
11085 struct sg_lb_stats tmp_sgs;
11086 unsigned long sum_util = 0;
11087 bool sg_overloaded = 0, sg_overutilized = 0;
11088
11089 do {
11090 struct sg_lb_stats *sgs = &tmp_sgs;
11091 int local_group;
11092
11093 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11094 if (local_group) {
11095 sds->local = sg;
11096 sgs = local;
11097
11098 if (env->idle != CPU_NEWLY_IDLE ||
11099 time_after_eq(jiffies, sg->sgc->next_update))
11100 update_group_capacity(env->sd, env->dst_cpu);
11101 }
11102
11103 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
11104
11105 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11106 sds->busiest = sg;
11107 sds->busiest_stat = *sgs;
11108 }
11109
11110 /* Now, start updating sd_lb_stats */
11111 sds->total_load += sgs->group_load;
11112 sds->total_capacity += sgs->group_capacity;
11113
11114 sum_util += sgs->group_util;
11115 sg = sg->next;
11116 } while (sg != env->sd->groups);
11117
11118 /*
11119 * Indicate that the child domain of the busiest group prefers tasks
11120 * go to a child's sibling domains first. NB the flags of a sched group
11121 * are those of the child domain.
11122 */
11123 if (sds->busiest)
11124 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11125
11126
11127 if (env->sd->flags & SD_NUMA)
11128 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11129
11130 if (!env->sd->parent) {
11131 /* update overload indicator if we are at root domain */
11132 set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11133
11134 /* Update over-utilization (tipping point, U >= 0) indicator */
11135 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11136 } else if (sg_overutilized) {
11137 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11138 }
11139
11140 update_idle_cpu_scan(env, sum_util);
11141 }
11142
11143 /**
11144 * calculate_imbalance - Calculate the amount of imbalance present within the
11145 * groups of a given sched_domain during load balance.
11146 * @env: load balance environment
11147 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11148 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11149 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11150 {
11151 struct sg_lb_stats *local, *busiest;
11152
11153 local = &sds->local_stat;
11154 busiest = &sds->busiest_stat;
11155
11156 if (busiest->group_type == group_misfit_task) {
11157 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11158 /* Set imbalance to allow misfit tasks to be balanced. */
11159 env->migration_type = migrate_misfit;
11160 env->imbalance = 1;
11161 } else {
11162 /*
11163 * Set load imbalance to allow moving task from cpu
11164 * with reduced capacity.
11165 */
11166 env->migration_type = migrate_load;
11167 env->imbalance = busiest->group_misfit_task_load;
11168 }
11169 return;
11170 }
11171
11172 if (busiest->group_type == group_asym_packing) {
11173 /*
11174 * In case of asym capacity, we will try to migrate all load to
11175 * the preferred CPU.
11176 */
11177 env->migration_type = migrate_task;
11178 env->imbalance = busiest->sum_h_nr_running;
11179 return;
11180 }
11181
11182 if (busiest->group_type == group_smt_balance) {
11183 /* Reduce number of tasks sharing CPU capacity */
11184 env->migration_type = migrate_task;
11185 env->imbalance = 1;
11186 return;
11187 }
11188
11189 if (busiest->group_type == group_imbalanced) {
11190 /*
11191 * In the group_imb case we cannot rely on group-wide averages
11192 * to ensure CPU-load equilibrium, try to move any task to fix
11193 * the imbalance. The next load balance will take care of
11194 * balancing back the system.
11195 */
11196 env->migration_type = migrate_task;
11197 env->imbalance = 1;
11198 return;
11199 }
11200
11201 /*
11202 * Try to use spare capacity of local group without overloading it or
11203 * emptying busiest.
11204 */
11205 if (local->group_type == group_has_spare) {
11206 if ((busiest->group_type > group_fully_busy) &&
11207 !(env->sd->flags & SD_SHARE_LLC)) {
11208 /*
11209 * If busiest is overloaded, try to fill spare
11210 * capacity. This might end up creating spare capacity
11211 * in busiest or busiest still being overloaded but
11212 * there is no simple way to directly compute the
11213 * amount of load to migrate in order to balance the
11214 * system.
11215 */
11216 env->migration_type = migrate_util;
11217 env->imbalance = max(local->group_capacity, local->group_util) -
11218 local->group_util;
11219
11220 /*
11221 * In some cases, the group's utilization is max or even
11222 * higher than capacity because of migrations but the
11223 * local CPU is (newly) idle. There is at least one
11224 * waiting task in this overloaded busiest group. Let's
11225 * try to pull it.
11226 */
11227 if (env->idle && env->imbalance == 0) {
11228 env->migration_type = migrate_task;
11229 env->imbalance = 1;
11230 }
11231
11232 return;
11233 }
11234
11235 if (busiest->group_weight == 1 || sds->prefer_sibling) {
11236 /*
11237 * When prefer sibling, evenly spread running tasks on
11238 * groups.
11239 */
11240 env->migration_type = migrate_task;
11241 env->imbalance = sibling_imbalance(env, sds, busiest, local);
11242 } else {
11243
11244 /*
11245 * If there is no overload, we just want to even the number of
11246 * idle CPUs.
11247 */
11248 env->migration_type = migrate_task;
11249 env->imbalance = max_t(long, 0,
11250 (local->idle_cpus - busiest->idle_cpus));
11251 }
11252
11253 #ifdef CONFIG_NUMA
11254 /* Consider allowing a small imbalance between NUMA groups */
11255 if (env->sd->flags & SD_NUMA) {
11256 env->imbalance = adjust_numa_imbalance(env->imbalance,
11257 local->sum_nr_running + 1,
11258 env->sd->imb_numa_nr);
11259 }
11260 #endif
11261
11262 /* Number of tasks to move to restore balance */
11263 env->imbalance >>= 1;
11264
11265 return;
11266 }
11267
11268 /*
11269 * Local is fully busy but has to take more load to relieve the
11270 * busiest group
11271 */
11272 if (local->group_type < group_overloaded) {
11273 /*
11274 * Local will become overloaded so the avg_load metrics are
11275 * finally needed.
11276 */
11277
11278 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11279 local->group_capacity;
11280
11281 /*
11282 * If the local group is more loaded than the selected
11283 * busiest group don't try to pull any tasks.
11284 */
11285 if (local->avg_load >= busiest->avg_load) {
11286 env->imbalance = 0;
11287 return;
11288 }
11289
11290 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11291 sds->total_capacity;
11292
11293 /*
11294 * If the local group is more loaded than the average system
11295 * load, don't try to pull any tasks.
11296 */
11297 if (local->avg_load >= sds->avg_load) {
11298 env->imbalance = 0;
11299 return;
11300 }
11301
11302 }
11303
11304 /*
11305 * Both group are or will become overloaded and we're trying to get all
11306 * the CPUs to the average_load, so we don't want to push ourselves
11307 * above the average load, nor do we wish to reduce the max loaded CPU
11308 * below the average load. At the same time, we also don't want to
11309 * reduce the group load below the group capacity. Thus we look for
11310 * the minimum possible imbalance.
11311 */
11312 env->migration_type = migrate_load;
11313 env->imbalance = min(
11314 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11315 (sds->avg_load - local->avg_load) * local->group_capacity
11316 ) / SCHED_CAPACITY_SCALE;
11317 }
11318
11319 /******* sched_balance_find_src_group() helpers end here *********************/
11320
11321 /*
11322 * Decision matrix according to the local and busiest group type:
11323 *
11324 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11325 * has_spare nr_idle balanced N/A N/A balanced balanced
11326 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
11327 * misfit_task force N/A N/A N/A N/A N/A
11328 * asym_packing force force N/A N/A force force
11329 * imbalanced force force N/A N/A force force
11330 * overloaded force force N/A N/A force avg_load
11331 *
11332 * N/A : Not Applicable because already filtered while updating
11333 * statistics.
11334 * balanced : The system is balanced for these 2 groups.
11335 * force : Calculate the imbalance as load migration is probably needed.
11336 * avg_load : Only if imbalance is significant enough.
11337 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
11338 * different in groups.
11339 */
11340
11341 /**
11342 * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11343 * if there is an imbalance.
11344 * @env: The load balancing environment.
11345 *
11346 * Also calculates the amount of runnable load which should be moved
11347 * to restore balance.
11348 *
11349 * Return: - The busiest group if imbalance exists.
11350 */
sched_balance_find_src_group(struct lb_env * env)11351 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11352 {
11353 struct sg_lb_stats *local, *busiest;
11354 struct sd_lb_stats sds;
11355
11356 init_sd_lb_stats(&sds);
11357
11358 /*
11359 * Compute the various statistics relevant for load balancing at
11360 * this level.
11361 */
11362 update_sd_lb_stats(env, &sds);
11363
11364 /* There is no busy sibling group to pull tasks from */
11365 if (!sds.busiest)
11366 goto out_balanced;
11367
11368 busiest = &sds.busiest_stat;
11369
11370 /* Misfit tasks should be dealt with regardless of the avg load */
11371 if (busiest->group_type == group_misfit_task)
11372 goto force_balance;
11373
11374 if (!is_rd_overutilized(env->dst_rq->rd) &&
11375 rcu_dereference(env->dst_rq->rd->pd))
11376 goto out_balanced;
11377
11378 /* ASYM feature bypasses nice load balance check */
11379 if (busiest->group_type == group_asym_packing)
11380 goto force_balance;
11381
11382 /*
11383 * If the busiest group is imbalanced the below checks don't
11384 * work because they assume all things are equal, which typically
11385 * isn't true due to cpus_ptr constraints and the like.
11386 */
11387 if (busiest->group_type == group_imbalanced)
11388 goto force_balance;
11389
11390 local = &sds.local_stat;
11391 /*
11392 * If the local group is busier than the selected busiest group
11393 * don't try and pull any tasks.
11394 */
11395 if (local->group_type > busiest->group_type)
11396 goto out_balanced;
11397
11398 /*
11399 * When groups are overloaded, use the avg_load to ensure fairness
11400 * between tasks.
11401 */
11402 if (local->group_type == group_overloaded) {
11403 /*
11404 * If the local group is more loaded than the selected
11405 * busiest group don't try to pull any tasks.
11406 */
11407 if (local->avg_load >= busiest->avg_load)
11408 goto out_balanced;
11409
11410 /* XXX broken for overlapping NUMA groups */
11411 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11412 sds.total_capacity;
11413
11414 /*
11415 * Don't pull any tasks if this group is already above the
11416 * domain average load.
11417 */
11418 if (local->avg_load >= sds.avg_load)
11419 goto out_balanced;
11420
11421 /*
11422 * If the busiest group is more loaded, use imbalance_pct to be
11423 * conservative.
11424 */
11425 if (100 * busiest->avg_load <=
11426 env->sd->imbalance_pct * local->avg_load)
11427 goto out_balanced;
11428 }
11429
11430 /*
11431 * Try to move all excess tasks to a sibling domain of the busiest
11432 * group's child domain.
11433 */
11434 if (sds.prefer_sibling && local->group_type == group_has_spare &&
11435 sibling_imbalance(env, &sds, busiest, local) > 1)
11436 goto force_balance;
11437
11438 if (busiest->group_type != group_overloaded) {
11439 if (!env->idle) {
11440 /*
11441 * If the busiest group is not overloaded (and as a
11442 * result the local one too) but this CPU is already
11443 * busy, let another idle CPU try to pull task.
11444 */
11445 goto out_balanced;
11446 }
11447
11448 if (busiest->group_type == group_smt_balance &&
11449 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11450 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
11451 goto force_balance;
11452 }
11453
11454 if (busiest->group_weight > 1 &&
11455 local->idle_cpus <= (busiest->idle_cpus + 1)) {
11456 /*
11457 * If the busiest group is not overloaded
11458 * and there is no imbalance between this and busiest
11459 * group wrt idle CPUs, it is balanced. The imbalance
11460 * becomes significant if the diff is greater than 1
11461 * otherwise we might end up to just move the imbalance
11462 * on another group. Of course this applies only if
11463 * there is more than 1 CPU per group.
11464 */
11465 goto out_balanced;
11466 }
11467
11468 if (busiest->sum_h_nr_running == 1) {
11469 /*
11470 * busiest doesn't have any tasks waiting to run
11471 */
11472 goto out_balanced;
11473 }
11474 }
11475
11476 force_balance:
11477 /* Looks like there is an imbalance. Compute it */
11478 calculate_imbalance(env, &sds);
11479 return env->imbalance ? sds.busiest : NULL;
11480
11481 out_balanced:
11482 env->imbalance = 0;
11483 return NULL;
11484 }
11485
11486 /*
11487 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11488 */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)11489 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11490 struct sched_group *group)
11491 {
11492 struct rq *busiest = NULL, *rq;
11493 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11494 unsigned int busiest_nr = 0;
11495 int i;
11496
11497 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11498 unsigned long capacity, load, util;
11499 unsigned int nr_running;
11500 enum fbq_type rt;
11501
11502 rq = cpu_rq(i);
11503 rt = fbq_classify_rq(rq);
11504
11505 /*
11506 * We classify groups/runqueues into three groups:
11507 * - regular: there are !numa tasks
11508 * - remote: there are numa tasks that run on the 'wrong' node
11509 * - all: there is no distinction
11510 *
11511 * In order to avoid migrating ideally placed numa tasks,
11512 * ignore those when there's better options.
11513 *
11514 * If we ignore the actual busiest queue to migrate another
11515 * task, the next balance pass can still reduce the busiest
11516 * queue by moving tasks around inside the node.
11517 *
11518 * If we cannot move enough load due to this classification
11519 * the next pass will adjust the group classification and
11520 * allow migration of more tasks.
11521 *
11522 * Both cases only affect the total convergence complexity.
11523 */
11524 if (rt > env->fbq_type)
11525 continue;
11526
11527 nr_running = rq->cfs.h_nr_runnable;
11528 if (!nr_running)
11529 continue;
11530
11531 capacity = capacity_of(i);
11532
11533 /*
11534 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11535 * eventually lead to active_balancing high->low capacity.
11536 * Higher per-CPU capacity is considered better than balancing
11537 * average load.
11538 */
11539 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11540 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11541 nr_running == 1)
11542 continue;
11543
11544 /*
11545 * Make sure we only pull tasks from a CPU of lower priority
11546 * when balancing between SMT siblings.
11547 *
11548 * If balancing between cores, let lower priority CPUs help
11549 * SMT cores with more than one busy sibling.
11550 */
11551 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11552 continue;
11553
11554 switch (env->migration_type) {
11555 case migrate_load:
11556 /*
11557 * When comparing with load imbalance, use cpu_load()
11558 * which is not scaled with the CPU capacity.
11559 */
11560 load = cpu_load(rq);
11561
11562 if (nr_running == 1 && load > env->imbalance &&
11563 !check_cpu_capacity(rq, env->sd))
11564 break;
11565
11566 /*
11567 * For the load comparisons with the other CPUs,
11568 * consider the cpu_load() scaled with the CPU
11569 * capacity, so that the load can be moved away
11570 * from the CPU that is potentially running at a
11571 * lower capacity.
11572 *
11573 * Thus we're looking for max(load_i / capacity_i),
11574 * crosswise multiplication to rid ourselves of the
11575 * division works out to:
11576 * load_i * capacity_j > load_j * capacity_i;
11577 * where j is our previous maximum.
11578 */
11579 if (load * busiest_capacity > busiest_load * capacity) {
11580 busiest_load = load;
11581 busiest_capacity = capacity;
11582 busiest = rq;
11583 }
11584 break;
11585
11586 case migrate_util:
11587 util = cpu_util_cfs_boost(i);
11588
11589 /*
11590 * Don't try to pull utilization from a CPU with one
11591 * running task. Whatever its utilization, we will fail
11592 * detach the task.
11593 */
11594 if (nr_running <= 1)
11595 continue;
11596
11597 if (busiest_util < util) {
11598 busiest_util = util;
11599 busiest = rq;
11600 }
11601 break;
11602
11603 case migrate_task:
11604 if (busiest_nr < nr_running) {
11605 busiest_nr = nr_running;
11606 busiest = rq;
11607 }
11608 break;
11609
11610 case migrate_misfit:
11611 /*
11612 * For ASYM_CPUCAPACITY domains with misfit tasks we
11613 * simply seek the "biggest" misfit task.
11614 */
11615 if (rq->misfit_task_load > busiest_load) {
11616 busiest_load = rq->misfit_task_load;
11617 busiest = rq;
11618 }
11619
11620 break;
11621
11622 }
11623 }
11624
11625 return busiest;
11626 }
11627
11628 /*
11629 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11630 * so long as it is large enough.
11631 */
11632 #define MAX_PINNED_INTERVAL 512
11633
11634 static inline bool
asym_active_balance(struct lb_env * env)11635 asym_active_balance(struct lb_env *env)
11636 {
11637 /*
11638 * ASYM_PACKING needs to force migrate tasks from busy but lower
11639 * priority CPUs in order to pack all tasks in the highest priority
11640 * CPUs. When done between cores, do it only if the whole core if the
11641 * whole core is idle.
11642 *
11643 * If @env::src_cpu is an SMT core with busy siblings, let
11644 * the lower priority @env::dst_cpu help it. Do not follow
11645 * CPU priority.
11646 */
11647 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11648 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11649 !sched_use_asym_prio(env->sd, env->src_cpu));
11650 }
11651
11652 static inline bool
imbalanced_active_balance(struct lb_env * env)11653 imbalanced_active_balance(struct lb_env *env)
11654 {
11655 struct sched_domain *sd = env->sd;
11656
11657 /*
11658 * The imbalanced case includes the case of pinned tasks preventing a fair
11659 * distribution of the load on the system but also the even distribution of the
11660 * threads on a system with spare capacity
11661 */
11662 if ((env->migration_type == migrate_task) &&
11663 (sd->nr_balance_failed > sd->cache_nice_tries+2))
11664 return 1;
11665
11666 return 0;
11667 }
11668
need_active_balance(struct lb_env * env)11669 static int need_active_balance(struct lb_env *env)
11670 {
11671 struct sched_domain *sd = env->sd;
11672
11673 if (asym_active_balance(env))
11674 return 1;
11675
11676 if (imbalanced_active_balance(env))
11677 return 1;
11678
11679 /*
11680 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11681 * It's worth migrating the task if the src_cpu's capacity is reduced
11682 * because of other sched_class or IRQs if more capacity stays
11683 * available on dst_cpu.
11684 */
11685 if (env->idle &&
11686 (env->src_rq->cfs.h_nr_runnable == 1)) {
11687 if ((check_cpu_capacity(env->src_rq, sd)) &&
11688 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11689 return 1;
11690 }
11691
11692 if (env->migration_type == migrate_misfit)
11693 return 1;
11694
11695 return 0;
11696 }
11697
11698 static int active_load_balance_cpu_stop(void *data);
11699
should_we_balance(struct lb_env * env)11700 static int should_we_balance(struct lb_env *env)
11701 {
11702 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11703 struct sched_group *sg = env->sd->groups;
11704 int cpu, idle_smt = -1;
11705
11706 /*
11707 * Ensure the balancing environment is consistent; can happen
11708 * when the softirq triggers 'during' hotplug.
11709 */
11710 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11711 return 0;
11712
11713 /*
11714 * In the newly idle case, we will allow all the CPUs
11715 * to do the newly idle load balance.
11716 *
11717 * However, we bail out if we already have tasks or a wakeup pending,
11718 * to optimize wakeup latency.
11719 */
11720 if (env->idle == CPU_NEWLY_IDLE) {
11721 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11722 return 0;
11723 return 1;
11724 }
11725
11726 cpumask_copy(swb_cpus, group_balance_mask(sg));
11727 /* Try to find first idle CPU */
11728 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11729 if (!idle_cpu(cpu))
11730 continue;
11731
11732 /*
11733 * Don't balance to idle SMT in busy core right away when
11734 * balancing cores, but remember the first idle SMT CPU for
11735 * later consideration. Find CPU on an idle core first.
11736 */
11737 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11738 if (idle_smt == -1)
11739 idle_smt = cpu;
11740 /*
11741 * If the core is not idle, and first SMT sibling which is
11742 * idle has been found, then its not needed to check other
11743 * SMT siblings for idleness:
11744 */
11745 #ifdef CONFIG_SCHED_SMT
11746 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11747 #endif
11748 continue;
11749 }
11750
11751 /*
11752 * Are we the first idle core in a non-SMT domain or higher,
11753 * or the first idle CPU in a SMT domain?
11754 */
11755 return cpu == env->dst_cpu;
11756 }
11757
11758 /* Are we the first idle CPU with busy siblings? */
11759 if (idle_smt != -1)
11760 return idle_smt == env->dst_cpu;
11761
11762 /* Are we the first CPU of this group ? */
11763 return group_balance_cpu(sg) == env->dst_cpu;
11764 }
11765
update_lb_imbalance_stat(struct lb_env * env,struct sched_domain * sd,enum cpu_idle_type idle)11766 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
11767 enum cpu_idle_type idle)
11768 {
11769 if (!schedstat_enabled())
11770 return;
11771
11772 switch (env->migration_type) {
11773 case migrate_load:
11774 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
11775 break;
11776 case migrate_util:
11777 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
11778 break;
11779 case migrate_task:
11780 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
11781 break;
11782 case migrate_misfit:
11783 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
11784 break;
11785 }
11786 }
11787
11788 /*
11789 * This flag serializes load-balancing passes over large domains
11790 * (above the NODE topology level) - only one load-balancing instance
11791 * may run at a time, to reduce overhead on very large systems with
11792 * lots of CPUs and large NUMA distances.
11793 *
11794 * - Note that load-balancing passes triggered while another one
11795 * is executing are skipped and not re-tried.
11796 *
11797 * - Also note that this does not serialize rebalance_domains()
11798 * execution, as non-SD_SERIALIZE domains will still be
11799 * load-balanced in parallel.
11800 */
11801 static atomic_t sched_balance_running = ATOMIC_INIT(0);
11802
11803 /*
11804 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11805 * tasks if there is an imbalance.
11806 */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11807 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
11808 struct sched_domain *sd, enum cpu_idle_type idle,
11809 int *continue_balancing)
11810 {
11811 int ld_moved, cur_ld_moved, active_balance = 0;
11812 struct sched_domain *sd_parent = sd->parent;
11813 struct sched_group *group;
11814 struct rq *busiest;
11815 struct rq_flags rf;
11816 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11817 struct lb_env env = {
11818 .sd = sd,
11819 .dst_cpu = this_cpu,
11820 .dst_rq = this_rq,
11821 .dst_grpmask = group_balance_mask(sd->groups),
11822 .idle = idle,
11823 .loop_break = SCHED_NR_MIGRATE_BREAK,
11824 .cpus = cpus,
11825 .fbq_type = all,
11826 .tasks = LIST_HEAD_INIT(env.tasks),
11827 };
11828 bool need_unlock = false;
11829
11830 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11831
11832 schedstat_inc(sd->lb_count[idle]);
11833
11834 redo:
11835 if (!should_we_balance(&env)) {
11836 *continue_balancing = 0;
11837 goto out_balanced;
11838 }
11839
11840 if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
11841 int zero = 0;
11842 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
11843 goto out_balanced;
11844
11845 need_unlock = true;
11846 }
11847
11848 group = sched_balance_find_src_group(&env);
11849 if (!group) {
11850 schedstat_inc(sd->lb_nobusyg[idle]);
11851 goto out_balanced;
11852 }
11853
11854 busiest = sched_balance_find_src_rq(&env, group);
11855 if (!busiest) {
11856 schedstat_inc(sd->lb_nobusyq[idle]);
11857 goto out_balanced;
11858 }
11859
11860 WARN_ON_ONCE(busiest == env.dst_rq);
11861
11862 update_lb_imbalance_stat(&env, sd, idle);
11863
11864 env.src_cpu = busiest->cpu;
11865 env.src_rq = busiest;
11866
11867 ld_moved = 0;
11868 /* Clear this flag as soon as we find a pullable task */
11869 env.flags |= LBF_ALL_PINNED;
11870 if (busiest->nr_running > 1) {
11871 /*
11872 * Attempt to move tasks. If sched_balance_find_src_group has found
11873 * an imbalance but busiest->nr_running <= 1, the group is
11874 * still unbalanced. ld_moved simply stays zero, so it is
11875 * correctly treated as an imbalance.
11876 */
11877 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11878
11879 more_balance:
11880 rq_lock_irqsave(busiest, &rf);
11881 update_rq_clock(busiest);
11882
11883 /*
11884 * cur_ld_moved - load moved in current iteration
11885 * ld_moved - cumulative load moved across iterations
11886 */
11887 cur_ld_moved = detach_tasks(&env);
11888
11889 /*
11890 * We've detached some tasks from busiest_rq. Every
11891 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11892 * unlock busiest->lock, and we are able to be sure
11893 * that nobody can manipulate the tasks in parallel.
11894 * See task_rq_lock() family for the details.
11895 */
11896
11897 rq_unlock(busiest, &rf);
11898
11899 if (cur_ld_moved) {
11900 attach_tasks(&env);
11901 ld_moved += cur_ld_moved;
11902 }
11903
11904 local_irq_restore(rf.flags);
11905
11906 if (env.flags & LBF_NEED_BREAK) {
11907 env.flags &= ~LBF_NEED_BREAK;
11908 goto more_balance;
11909 }
11910
11911 /*
11912 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11913 * us and move them to an alternate dst_cpu in our sched_group
11914 * where they can run. The upper limit on how many times we
11915 * iterate on same src_cpu is dependent on number of CPUs in our
11916 * sched_group.
11917 *
11918 * This changes load balance semantics a bit on who can move
11919 * load to a given_cpu. In addition to the given_cpu itself
11920 * (or a ilb_cpu acting on its behalf where given_cpu is
11921 * nohz-idle), we now have balance_cpu in a position to move
11922 * load to given_cpu. In rare situations, this may cause
11923 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11924 * _independently_ and at _same_ time to move some load to
11925 * given_cpu) causing excess load to be moved to given_cpu.
11926 * This however should not happen so much in practice and
11927 * moreover subsequent load balance cycles should correct the
11928 * excess load moved.
11929 */
11930 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11931
11932 /* Prevent to re-select dst_cpu via env's CPUs */
11933 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11934
11935 env.dst_rq = cpu_rq(env.new_dst_cpu);
11936 env.dst_cpu = env.new_dst_cpu;
11937 env.flags &= ~LBF_DST_PINNED;
11938 env.loop = 0;
11939 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11940
11941 /*
11942 * Go back to "more_balance" rather than "redo" since we
11943 * need to continue with same src_cpu.
11944 */
11945 goto more_balance;
11946 }
11947
11948 /*
11949 * We failed to reach balance because of affinity.
11950 */
11951 if (sd_parent) {
11952 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11953
11954 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11955 *group_imbalance = 1;
11956 }
11957
11958 /* All tasks on this runqueue were pinned by CPU affinity */
11959 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11960 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11961 /*
11962 * Attempting to continue load balancing at the current
11963 * sched_domain level only makes sense if there are
11964 * active CPUs remaining as possible busiest CPUs to
11965 * pull load from which are not contained within the
11966 * destination group that is receiving any migrated
11967 * load.
11968 */
11969 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11970 env.loop = 0;
11971 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11972 goto redo;
11973 }
11974 goto out_all_pinned;
11975 }
11976 }
11977
11978 if (!ld_moved) {
11979 schedstat_inc(sd->lb_failed[idle]);
11980 /*
11981 * Increment the failure counter only on periodic balance.
11982 * We do not want newidle balance, which can be very
11983 * frequent, pollute the failure counter causing
11984 * excessive cache_hot migrations and active balances.
11985 *
11986 * Similarly for migration_misfit which is not related to
11987 * load/util migration, don't pollute nr_balance_failed.
11988 */
11989 if (idle != CPU_NEWLY_IDLE &&
11990 env.migration_type != migrate_misfit)
11991 sd->nr_balance_failed++;
11992
11993 if (need_active_balance(&env)) {
11994 unsigned long flags;
11995
11996 raw_spin_rq_lock_irqsave(busiest, flags);
11997
11998 /*
11999 * Don't kick the active_load_balance_cpu_stop,
12000 * if the curr task on busiest CPU can't be
12001 * moved to this_cpu:
12002 */
12003 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
12004 raw_spin_rq_unlock_irqrestore(busiest, flags);
12005 goto out_one_pinned;
12006 }
12007
12008 /* Record that we found at least one task that could run on this_cpu */
12009 env.flags &= ~LBF_ALL_PINNED;
12010
12011 /*
12012 * ->active_balance synchronizes accesses to
12013 * ->active_balance_work. Once set, it's cleared
12014 * only after active load balance is finished.
12015 */
12016 if (!busiest->active_balance) {
12017 busiest->active_balance = 1;
12018 busiest->push_cpu = this_cpu;
12019 active_balance = 1;
12020 }
12021
12022 preempt_disable();
12023 raw_spin_rq_unlock_irqrestore(busiest, flags);
12024 if (active_balance) {
12025 stop_one_cpu_nowait(cpu_of(busiest),
12026 active_load_balance_cpu_stop, busiest,
12027 &busiest->active_balance_work);
12028 }
12029 preempt_enable();
12030 }
12031 } else {
12032 sd->nr_balance_failed = 0;
12033 }
12034
12035 if (likely(!active_balance) || need_active_balance(&env)) {
12036 /* We were unbalanced, so reset the balancing interval */
12037 sd->balance_interval = sd->min_interval;
12038 }
12039
12040 goto out;
12041
12042 out_balanced:
12043 /*
12044 * We reach balance although we may have faced some affinity
12045 * constraints. Clear the imbalance flag only if other tasks got
12046 * a chance to move and fix the imbalance.
12047 */
12048 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
12049 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12050
12051 if (*group_imbalance)
12052 *group_imbalance = 0;
12053 }
12054
12055 out_all_pinned:
12056 /*
12057 * We reach balance because all tasks are pinned at this level so
12058 * we can't migrate them. Let the imbalance flag set so parent level
12059 * can try to migrate them.
12060 */
12061 schedstat_inc(sd->lb_balanced[idle]);
12062
12063 sd->nr_balance_failed = 0;
12064
12065 out_one_pinned:
12066 ld_moved = 0;
12067
12068 /*
12069 * sched_balance_newidle() disregards balance intervals, so we could
12070 * repeatedly reach this code, which would lead to balance_interval
12071 * skyrocketing in a short amount of time. Skip the balance_interval
12072 * increase logic to avoid that.
12073 *
12074 * Similarly misfit migration which is not necessarily an indication of
12075 * the system being busy and requires lb to backoff to let it settle
12076 * down.
12077 */
12078 if (env.idle == CPU_NEWLY_IDLE ||
12079 env.migration_type == migrate_misfit)
12080 goto out;
12081
12082 /* tune up the balancing interval */
12083 if ((env.flags & LBF_ALL_PINNED &&
12084 sd->balance_interval < MAX_PINNED_INTERVAL) ||
12085 sd->balance_interval < sd->max_interval)
12086 sd->balance_interval *= 2;
12087 out:
12088 if (need_unlock)
12089 atomic_set_release(&sched_balance_running, 0);
12090
12091 return ld_moved;
12092 }
12093
12094 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)12095 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
12096 {
12097 unsigned long interval = sd->balance_interval;
12098
12099 if (cpu_busy)
12100 interval *= sd->busy_factor;
12101
12102 /* scale ms to jiffies */
12103 interval = msecs_to_jiffies(interval);
12104
12105 /*
12106 * Reduce likelihood of busy balancing at higher domains racing with
12107 * balancing at lower domains by preventing their balancing periods
12108 * from being multiples of each other.
12109 */
12110 if (cpu_busy)
12111 interval -= 1;
12112
12113 interval = clamp(interval, 1UL, max_load_balance_interval);
12114
12115 return interval;
12116 }
12117
12118 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)12119 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12120 {
12121 unsigned long interval, next;
12122
12123 /* used by idle balance, so cpu_busy = 0 */
12124 interval = get_sd_balance_interval(sd, 0);
12125 next = sd->last_balance + interval;
12126
12127 if (time_after(*next_balance, next))
12128 *next_balance = next;
12129 }
12130
12131 /*
12132 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12133 * running tasks off the busiest CPU onto idle CPUs. It requires at
12134 * least 1 task to be running on each physical CPU where possible, and
12135 * avoids physical / logical imbalances.
12136 */
active_load_balance_cpu_stop(void * data)12137 static int active_load_balance_cpu_stop(void *data)
12138 {
12139 struct rq *busiest_rq = data;
12140 int busiest_cpu = cpu_of(busiest_rq);
12141 int target_cpu = busiest_rq->push_cpu;
12142 struct rq *target_rq = cpu_rq(target_cpu);
12143 struct sched_domain *sd;
12144 struct task_struct *p = NULL;
12145 struct rq_flags rf;
12146
12147 rq_lock_irq(busiest_rq, &rf);
12148 /*
12149 * Between queueing the stop-work and running it is a hole in which
12150 * CPUs can become inactive. We should not move tasks from or to
12151 * inactive CPUs.
12152 */
12153 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12154 goto out_unlock;
12155
12156 /* Make sure the requested CPU hasn't gone down in the meantime: */
12157 if (unlikely(busiest_cpu != smp_processor_id() ||
12158 !busiest_rq->active_balance))
12159 goto out_unlock;
12160
12161 /* Is there any task to move? */
12162 if (busiest_rq->nr_running <= 1)
12163 goto out_unlock;
12164
12165 /*
12166 * This condition is "impossible", if it occurs
12167 * we need to fix it. Originally reported by
12168 * Bjorn Helgaas on a 128-CPU setup.
12169 */
12170 WARN_ON_ONCE(busiest_rq == target_rq);
12171
12172 /* Search for an sd spanning us and the target CPU. */
12173 rcu_read_lock();
12174 for_each_domain(target_cpu, sd) {
12175 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12176 break;
12177 }
12178
12179 if (likely(sd)) {
12180 struct lb_env env = {
12181 .sd = sd,
12182 .dst_cpu = target_cpu,
12183 .dst_rq = target_rq,
12184 .src_cpu = busiest_rq->cpu,
12185 .src_rq = busiest_rq,
12186 .idle = CPU_IDLE,
12187 .flags = LBF_ACTIVE_LB,
12188 };
12189
12190 schedstat_inc(sd->alb_count);
12191 update_rq_clock(busiest_rq);
12192
12193 p = detach_one_task(&env);
12194 if (p) {
12195 schedstat_inc(sd->alb_pushed);
12196 /* Active balancing done, reset the failure counter. */
12197 sd->nr_balance_failed = 0;
12198 } else {
12199 schedstat_inc(sd->alb_failed);
12200 }
12201 }
12202 rcu_read_unlock();
12203 out_unlock:
12204 busiest_rq->active_balance = 0;
12205 rq_unlock(busiest_rq, &rf);
12206
12207 if (p)
12208 attach_one_task(target_rq, p);
12209
12210 local_irq_enable();
12211
12212 return 0;
12213 }
12214
12215 /*
12216 * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12217 * This trades load-balance latency on larger machines for less cross talk.
12218 */
update_max_interval(void)12219 void update_max_interval(void)
12220 {
12221 max_load_balance_interval = HZ*num_online_cpus()/10;
12222 }
12223
update_newidle_stats(struct sched_domain * sd,unsigned int success)12224 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
12225 {
12226 sd->newidle_call++;
12227 sd->newidle_success += success;
12228
12229 if (sd->newidle_call >= 1024) {
12230 sd->newidle_ratio = sd->newidle_success;
12231 sd->newidle_call /= 2;
12232 sd->newidle_success /= 2;
12233 }
12234 }
12235
12236 static inline bool
update_newidle_cost(struct sched_domain * sd,u64 cost,unsigned int success)12237 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
12238 {
12239 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
12240 unsigned long now = jiffies;
12241
12242 if (cost)
12243 update_newidle_stats(sd, success);
12244
12245 if (cost > sd->max_newidle_lb_cost) {
12246 /*
12247 * Track max cost of a domain to make sure to not delay the
12248 * next wakeup on the CPU.
12249 */
12250 sd->max_newidle_lb_cost = cost;
12251 sd->last_decay_max_lb_cost = now;
12252
12253 } else if (time_after(now, next_decay)) {
12254 /*
12255 * Decay the newidle max times by ~1% per second to ensure that
12256 * it is not outdated and the current max cost is actually
12257 * shorter.
12258 */
12259 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12260 sd->last_decay_max_lb_cost = now;
12261 return true;
12262 }
12263
12264 return false;
12265 }
12266
12267 /*
12268 * It checks each scheduling domain to see if it is due to be balanced,
12269 * and initiates a balancing operation if so.
12270 *
12271 * Balancing parameters are set up in init_sched_domains.
12272 */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)12273 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12274 {
12275 int continue_balancing = 1;
12276 int cpu = rq->cpu;
12277 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12278 unsigned long interval;
12279 struct sched_domain *sd;
12280 /* Earliest time when we have to do rebalance again */
12281 unsigned long next_balance = jiffies + 60*HZ;
12282 int update_next_balance = 0;
12283 int need_decay = 0;
12284 u64 max_cost = 0;
12285
12286 rcu_read_lock();
12287 for_each_domain(cpu, sd) {
12288 /*
12289 * Decay the newidle max times here because this is a regular
12290 * visit to all the domains.
12291 */
12292 need_decay = update_newidle_cost(sd, 0, 0);
12293 max_cost += sd->max_newidle_lb_cost;
12294
12295 /*
12296 * Stop the load balance at this level. There is another
12297 * CPU in our sched group which is doing load balancing more
12298 * actively.
12299 */
12300 if (!continue_balancing) {
12301 if (need_decay)
12302 continue;
12303 break;
12304 }
12305
12306 interval = get_sd_balance_interval(sd, busy);
12307 if (time_after_eq(jiffies, sd->last_balance + interval)) {
12308 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12309 /*
12310 * The LBF_DST_PINNED logic could have changed
12311 * env->dst_cpu, so we can't know our idle
12312 * state even if we migrated tasks. Update it.
12313 */
12314 idle = idle_cpu(cpu);
12315 busy = !idle && !sched_idle_cpu(cpu);
12316 }
12317 sd->last_balance = jiffies;
12318 interval = get_sd_balance_interval(sd, busy);
12319 }
12320 if (time_after(next_balance, sd->last_balance + interval)) {
12321 next_balance = sd->last_balance + interval;
12322 update_next_balance = 1;
12323 }
12324 }
12325 if (need_decay) {
12326 /*
12327 * Ensure the rq-wide value also decays but keep it at a
12328 * reasonable floor to avoid funnies with rq->avg_idle.
12329 */
12330 rq->max_idle_balance_cost =
12331 max((u64)sysctl_sched_migration_cost, max_cost);
12332 }
12333 rcu_read_unlock();
12334
12335 /*
12336 * next_balance will be updated only when there is a need.
12337 * When the cpu is attached to null domain for ex, it will not be
12338 * updated.
12339 */
12340 if (likely(update_next_balance))
12341 rq->next_balance = next_balance;
12342
12343 }
12344
on_null_domain(struct rq * rq)12345 static inline int on_null_domain(struct rq *rq)
12346 {
12347 return unlikely(!rcu_dereference_sched(rq->sd));
12348 }
12349
12350 #ifdef CONFIG_NO_HZ_COMMON
12351 /*
12352 * NOHZ idle load balancing (ILB) details:
12353 *
12354 * - When one of the busy CPUs notices that there may be an idle rebalancing
12355 * needed, they will kick the idle load balancer, which then does idle
12356 * load balancing for all the idle CPUs.
12357 */
find_new_ilb(void)12358 static inline int find_new_ilb(void)
12359 {
12360 const struct cpumask *hk_mask;
12361 int ilb_cpu;
12362
12363 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE);
12364
12365 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12366
12367 if (ilb_cpu == smp_processor_id())
12368 continue;
12369
12370 if (idle_cpu(ilb_cpu))
12371 return ilb_cpu;
12372 }
12373
12374 return -1;
12375 }
12376
12377 /*
12378 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12379 * SMP function call (IPI).
12380 *
12381 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set
12382 * (if there is one).
12383 */
kick_ilb(unsigned int flags)12384 static void kick_ilb(unsigned int flags)
12385 {
12386 int ilb_cpu;
12387
12388 /*
12389 * Increase nohz.next_balance only when if full ilb is triggered but
12390 * not if we only update stats.
12391 */
12392 if (flags & NOHZ_BALANCE_KICK)
12393 nohz.next_balance = jiffies+1;
12394
12395 ilb_cpu = find_new_ilb();
12396 if (ilb_cpu < 0)
12397 return;
12398
12399 /*
12400 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12401 * i.e. all bits in flags are already set in ilb_cpu.
12402 */
12403 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12404 return;
12405
12406 /*
12407 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12408 * the first flag owns it; cleared by nohz_csd_func().
12409 */
12410 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12411 if (flags & NOHZ_KICK_MASK)
12412 return;
12413
12414 /*
12415 * This way we generate an IPI on the target CPU which
12416 * is idle, and the softirq performing NOHZ idle load balancing
12417 * will be run before returning from the IPI.
12418 */
12419 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12420 }
12421
12422 /*
12423 * Current decision point for kicking the idle load balancer in the presence
12424 * of idle CPUs in the system.
12425 */
nohz_balancer_kick(struct rq * rq)12426 static void nohz_balancer_kick(struct rq *rq)
12427 {
12428 unsigned long now = jiffies;
12429 struct sched_domain_shared *sds;
12430 struct sched_domain *sd;
12431 int nr_busy, i, cpu = rq->cpu;
12432 unsigned int flags = 0;
12433
12434 if (unlikely(rq->idle_balance))
12435 return;
12436
12437 /*
12438 * We may be recently in ticked or tickless idle mode. At the first
12439 * busy tick after returning from idle, we will update the busy stats.
12440 */
12441 nohz_balance_exit_idle(rq);
12442
12443 /*
12444 * None are in tickless mode and hence no need for NOHZ idle load
12445 * balancing:
12446 */
12447 if (likely(!atomic_read(&nohz.nr_cpus)))
12448 return;
12449
12450 if (READ_ONCE(nohz.has_blocked) &&
12451 time_after(now, READ_ONCE(nohz.next_blocked)))
12452 flags = NOHZ_STATS_KICK;
12453
12454 if (time_before(now, nohz.next_balance))
12455 goto out;
12456
12457 if (rq->nr_running >= 2) {
12458 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12459 goto out;
12460 }
12461
12462 rcu_read_lock();
12463
12464 sd = rcu_dereference(rq->sd);
12465 if (sd) {
12466 /*
12467 * If there's a runnable CFS task and the current CPU has reduced
12468 * capacity, kick the ILB to see if there's a better CPU to run on:
12469 */
12470 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
12471 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12472 goto unlock;
12473 }
12474 }
12475
12476 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
12477 if (sd) {
12478 /*
12479 * When ASYM_PACKING; see if there's a more preferred CPU
12480 * currently idle; in which case, kick the ILB to move tasks
12481 * around.
12482 *
12483 * When balancing between cores, all the SMT siblings of the
12484 * preferred CPU must be idle.
12485 */
12486 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12487 if (sched_asym(sd, i, cpu)) {
12488 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12489 goto unlock;
12490 }
12491 }
12492 }
12493
12494 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
12495 if (sd) {
12496 /*
12497 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12498 * to run the misfit task on.
12499 */
12500 if (check_misfit_status(rq)) {
12501 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12502 goto unlock;
12503 }
12504
12505 /*
12506 * For asymmetric systems, we do not want to nicely balance
12507 * cache use, instead we want to embrace asymmetry and only
12508 * ensure tasks have enough CPU capacity.
12509 *
12510 * Skip the LLC logic because it's not relevant in that case.
12511 */
12512 goto unlock;
12513 }
12514
12515 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
12516 if (sds) {
12517 /*
12518 * If there is an imbalance between LLC domains (IOW we could
12519 * increase the overall cache utilization), we need a less-loaded LLC
12520 * domain to pull some load from. Likewise, we may need to spread
12521 * load within the current LLC domain (e.g. packed SMT cores but
12522 * other CPUs are idle). We can't really know from here how busy
12523 * the others are - so just get a NOHZ balance going if it looks
12524 * like this LLC domain has tasks we could move.
12525 */
12526 nr_busy = atomic_read(&sds->nr_busy_cpus);
12527 if (nr_busy > 1) {
12528 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12529 goto unlock;
12530 }
12531 }
12532 unlock:
12533 rcu_read_unlock();
12534 out:
12535 if (READ_ONCE(nohz.needs_update))
12536 flags |= NOHZ_NEXT_KICK;
12537
12538 if (flags)
12539 kick_ilb(flags);
12540 }
12541
set_cpu_sd_state_busy(int cpu)12542 static void set_cpu_sd_state_busy(int cpu)
12543 {
12544 struct sched_domain *sd;
12545
12546 rcu_read_lock();
12547 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12548
12549 if (!sd || !sd->nohz_idle)
12550 goto unlock;
12551 sd->nohz_idle = 0;
12552
12553 atomic_inc(&sd->shared->nr_busy_cpus);
12554 unlock:
12555 rcu_read_unlock();
12556 }
12557
nohz_balance_exit_idle(struct rq * rq)12558 void nohz_balance_exit_idle(struct rq *rq)
12559 {
12560 WARN_ON_ONCE(rq != this_rq());
12561
12562 if (likely(!rq->nohz_tick_stopped))
12563 return;
12564
12565 rq->nohz_tick_stopped = 0;
12566 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12567 atomic_dec(&nohz.nr_cpus);
12568
12569 set_cpu_sd_state_busy(rq->cpu);
12570 }
12571
set_cpu_sd_state_idle(int cpu)12572 static void set_cpu_sd_state_idle(int cpu)
12573 {
12574 struct sched_domain *sd;
12575
12576 rcu_read_lock();
12577 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12578
12579 if (!sd || sd->nohz_idle)
12580 goto unlock;
12581 sd->nohz_idle = 1;
12582
12583 atomic_dec(&sd->shared->nr_busy_cpus);
12584 unlock:
12585 rcu_read_unlock();
12586 }
12587
12588 /*
12589 * This routine will record that the CPU is going idle with tick stopped.
12590 * This info will be used in performing idle load balancing in the future.
12591 */
nohz_balance_enter_idle(int cpu)12592 void nohz_balance_enter_idle(int cpu)
12593 {
12594 struct rq *rq = cpu_rq(cpu);
12595
12596 WARN_ON_ONCE(cpu != smp_processor_id());
12597
12598 /* If this CPU is going down, then nothing needs to be done: */
12599 if (!cpu_active(cpu))
12600 return;
12601
12602 /*
12603 * Can be set safely without rq->lock held
12604 * If a clear happens, it will have evaluated last additions because
12605 * rq->lock is held during the check and the clear
12606 */
12607 rq->has_blocked_load = 1;
12608
12609 /*
12610 * The tick is still stopped but load could have been added in the
12611 * meantime. We set the nohz.has_blocked flag to trig a check of the
12612 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12613 * of nohz.has_blocked can only happen after checking the new load
12614 */
12615 if (rq->nohz_tick_stopped)
12616 goto out;
12617
12618 /* If we're a completely isolated CPU, we don't play: */
12619 if (on_null_domain(rq))
12620 return;
12621
12622 rq->nohz_tick_stopped = 1;
12623
12624 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12625 atomic_inc(&nohz.nr_cpus);
12626
12627 /*
12628 * Ensures that if nohz_idle_balance() fails to observe our
12629 * @idle_cpus_mask store, it must observe the @has_blocked
12630 * and @needs_update stores.
12631 */
12632 smp_mb__after_atomic();
12633
12634 set_cpu_sd_state_idle(cpu);
12635
12636 WRITE_ONCE(nohz.needs_update, 1);
12637 out:
12638 /*
12639 * Each time a cpu enter idle, we assume that it has blocked load and
12640 * enable the periodic update of the load of idle CPUs
12641 */
12642 WRITE_ONCE(nohz.has_blocked, 1);
12643 }
12644
update_nohz_stats(struct rq * rq)12645 static bool update_nohz_stats(struct rq *rq)
12646 {
12647 unsigned int cpu = rq->cpu;
12648
12649 if (!rq->has_blocked_load)
12650 return false;
12651
12652 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12653 return false;
12654
12655 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12656 return true;
12657
12658 sched_balance_update_blocked_averages(cpu);
12659
12660 return rq->has_blocked_load;
12661 }
12662
12663 /*
12664 * Internal function that runs load balance for all idle CPUs. The load balance
12665 * can be a simple update of blocked load or a complete load balance with
12666 * tasks movement depending of flags.
12667 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12668 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12669 {
12670 /* Earliest time when we have to do rebalance again */
12671 unsigned long now = jiffies;
12672 unsigned long next_balance = now + 60*HZ;
12673 bool has_blocked_load = false;
12674 int update_next_balance = 0;
12675 int this_cpu = this_rq->cpu;
12676 int balance_cpu;
12677 struct rq *rq;
12678
12679 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12680
12681 /*
12682 * We assume there will be no idle load after this update and clear
12683 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12684 * set the has_blocked flag and trigger another update of idle load.
12685 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12686 * setting the flag, we are sure to not clear the state and not
12687 * check the load of an idle cpu.
12688 *
12689 * Same applies to idle_cpus_mask vs needs_update.
12690 */
12691 if (flags & NOHZ_STATS_KICK)
12692 WRITE_ONCE(nohz.has_blocked, 0);
12693 if (flags & NOHZ_NEXT_KICK)
12694 WRITE_ONCE(nohz.needs_update, 0);
12695
12696 /*
12697 * Ensures that if we miss the CPU, we must see the has_blocked
12698 * store from nohz_balance_enter_idle().
12699 */
12700 smp_mb();
12701
12702 /*
12703 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12704 * chance for other idle cpu to pull load.
12705 */
12706 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
12707 if (!idle_cpu(balance_cpu))
12708 continue;
12709
12710 /*
12711 * If this CPU gets work to do, stop the load balancing
12712 * work being done for other CPUs. Next load
12713 * balancing owner will pick it up.
12714 */
12715 if (!idle_cpu(this_cpu) && need_resched()) {
12716 if (flags & NOHZ_STATS_KICK)
12717 has_blocked_load = true;
12718 if (flags & NOHZ_NEXT_KICK)
12719 WRITE_ONCE(nohz.needs_update, 1);
12720 goto abort;
12721 }
12722
12723 rq = cpu_rq(balance_cpu);
12724
12725 if (flags & NOHZ_STATS_KICK)
12726 has_blocked_load |= update_nohz_stats(rq);
12727
12728 /*
12729 * If time for next balance is due,
12730 * do the balance.
12731 */
12732 if (time_after_eq(jiffies, rq->next_balance)) {
12733 struct rq_flags rf;
12734
12735 rq_lock_irqsave(rq, &rf);
12736 update_rq_clock(rq);
12737 rq_unlock_irqrestore(rq, &rf);
12738
12739 if (flags & NOHZ_BALANCE_KICK)
12740 sched_balance_domains(rq, CPU_IDLE);
12741 }
12742
12743 if (time_after(next_balance, rq->next_balance)) {
12744 next_balance = rq->next_balance;
12745 update_next_balance = 1;
12746 }
12747 }
12748
12749 /*
12750 * next_balance will be updated only when there is a need.
12751 * When the CPU is attached to null domain for ex, it will not be
12752 * updated.
12753 */
12754 if (likely(update_next_balance))
12755 nohz.next_balance = next_balance;
12756
12757 if (flags & NOHZ_STATS_KICK)
12758 WRITE_ONCE(nohz.next_blocked,
12759 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12760
12761 abort:
12762 /* There is still blocked load, enable periodic update */
12763 if (has_blocked_load)
12764 WRITE_ONCE(nohz.has_blocked, 1);
12765 }
12766
12767 /*
12768 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12769 * rebalancing for all the CPUs for whom scheduler ticks are stopped.
12770 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12771 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12772 {
12773 unsigned int flags = this_rq->nohz_idle_balance;
12774
12775 if (!flags)
12776 return false;
12777
12778 this_rq->nohz_idle_balance = 0;
12779
12780 if (idle != CPU_IDLE)
12781 return false;
12782
12783 _nohz_idle_balance(this_rq, flags);
12784
12785 return true;
12786 }
12787
12788 /*
12789 * Check if we need to directly run the ILB for updating blocked load before
12790 * entering idle state. Here we run ILB directly without issuing IPIs.
12791 *
12792 * Note that when this function is called, the tick may not yet be stopped on
12793 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
12794 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
12795 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
12796 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
12797 * called from this function on (this) CPU that's not yet in the mask. That's
12798 * OK because the goal of nohz_run_idle_balance() is to run ILB only for
12799 * updating the blocked load of already idle CPUs without waking up one of
12800 * those idle CPUs and outside the preempt disable / IRQ off phase of the local
12801 * cpu about to enter idle, because it can take a long time.
12802 */
nohz_run_idle_balance(int cpu)12803 void nohz_run_idle_balance(int cpu)
12804 {
12805 unsigned int flags;
12806
12807 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12808
12809 /*
12810 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12811 * (i.e. NOHZ_STATS_KICK set) and will do the same.
12812 */
12813 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12814 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12815 }
12816
nohz_newidle_balance(struct rq * this_rq)12817 static void nohz_newidle_balance(struct rq *this_rq)
12818 {
12819 int this_cpu = this_rq->cpu;
12820
12821 /* Will wake up very soon. No time for doing anything else*/
12822 if (this_rq->avg_idle < sysctl_sched_migration_cost)
12823 return;
12824
12825 /* Don't need to update blocked load of idle CPUs*/
12826 if (!READ_ONCE(nohz.has_blocked) ||
12827 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12828 return;
12829
12830 /*
12831 * Set the need to trigger ILB in order to update blocked load
12832 * before entering idle state.
12833 */
12834 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12835 }
12836
12837 #else /* !CONFIG_NO_HZ_COMMON: */
nohz_balancer_kick(struct rq * rq)12838 static inline void nohz_balancer_kick(struct rq *rq) { }
12839
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12840 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12841 {
12842 return false;
12843 }
12844
nohz_newidle_balance(struct rq * this_rq)12845 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12846 #endif /* !CONFIG_NO_HZ_COMMON */
12847
12848 /*
12849 * sched_balance_newidle is called by schedule() if this_cpu is about to become
12850 * idle. Attempts to pull tasks from other CPUs.
12851 *
12852 * Returns:
12853 * < 0 - we released the lock and there are !fair tasks present
12854 * 0 - failed, no new tasks
12855 * > 0 - success, new (fair) tasks present
12856 */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)12857 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
12858 {
12859 unsigned long next_balance = jiffies + HZ;
12860 int this_cpu = this_rq->cpu;
12861 int continue_balancing = 1;
12862 u64 t0, t1, curr_cost = 0;
12863 struct sched_domain *sd;
12864 int pulled_task = 0;
12865
12866 update_misfit_status(NULL, this_rq);
12867
12868 /*
12869 * There is a task waiting to run. No need to search for one.
12870 * Return 0; the task will be enqueued when switching to idle.
12871 */
12872 if (this_rq->ttwu_pending)
12873 return 0;
12874
12875 /*
12876 * We must set idle_stamp _before_ calling sched_balance_rq()
12877 * for CPU_NEWLY_IDLE, such that we measure the this duration
12878 * as idle time.
12879 */
12880 this_rq->idle_stamp = rq_clock(this_rq);
12881
12882 /*
12883 * Do not pull tasks towards !active CPUs...
12884 */
12885 if (!cpu_active(this_cpu))
12886 return 0;
12887
12888 /*
12889 * This is OK, because current is on_cpu, which avoids it being picked
12890 * for load-balance and preemption/IRQs are still disabled avoiding
12891 * further scheduler activity on it and we're being very careful to
12892 * re-start the picking loop.
12893 */
12894 rq_unpin_lock(this_rq, rf);
12895
12896 rcu_read_lock();
12897 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12898 if (!sd) {
12899 rcu_read_unlock();
12900 goto out;
12901 }
12902
12903 if (!get_rd_overloaded(this_rq->rd) ||
12904 this_rq->avg_idle < sd->max_newidle_lb_cost) {
12905
12906 update_next_balance(sd, &next_balance);
12907 rcu_read_unlock();
12908 goto out;
12909 }
12910 rcu_read_unlock();
12911
12912 rq_modified_clear(this_rq);
12913 raw_spin_rq_unlock(this_rq);
12914
12915 t0 = sched_clock_cpu(this_cpu);
12916 sched_balance_update_blocked_averages(this_cpu);
12917
12918 rcu_read_lock();
12919 for_each_domain(this_cpu, sd) {
12920 u64 domain_cost;
12921
12922 update_next_balance(sd, &next_balance);
12923
12924 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12925 break;
12926
12927 if (sd->flags & SD_BALANCE_NEWIDLE) {
12928 unsigned int weight = 1;
12929
12930 if (sched_feat(NI_RANDOM)) {
12931 /*
12932 * Throw a 1k sided dice; and only run
12933 * newidle_balance according to the success
12934 * rate.
12935 */
12936 u32 d1k = sched_rng() % 1024;
12937 weight = 1 + sd->newidle_ratio;
12938 if (d1k > weight) {
12939 update_newidle_stats(sd, 0);
12940 continue;
12941 }
12942 weight = (1024 + weight/2) / weight;
12943 }
12944
12945 pulled_task = sched_balance_rq(this_cpu, this_rq,
12946 sd, CPU_NEWLY_IDLE,
12947 &continue_balancing);
12948
12949 t1 = sched_clock_cpu(this_cpu);
12950 domain_cost = t1 - t0;
12951 curr_cost += domain_cost;
12952 t0 = t1;
12953
12954 /*
12955 * Track max cost of a domain to make sure to not delay the
12956 * next wakeup on the CPU.
12957 */
12958 update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
12959 }
12960
12961 /*
12962 * Stop searching for tasks to pull if there are
12963 * now runnable tasks on this rq.
12964 */
12965 if (pulled_task || !continue_balancing)
12966 break;
12967 }
12968 rcu_read_unlock();
12969
12970 raw_spin_rq_lock(this_rq);
12971
12972 if (curr_cost > this_rq->max_idle_balance_cost)
12973 this_rq->max_idle_balance_cost = curr_cost;
12974
12975 /*
12976 * While browsing the domains, we released the rq lock, a task could
12977 * have been enqueued in the meantime. Since we're not going idle,
12978 * pretend we pulled a task.
12979 */
12980 if (this_rq->cfs.h_nr_queued && !pulled_task)
12981 pulled_task = 1;
12982
12983 /* If a higher prio class was modified, restart the pick */
12984 if (rq_modified_above(this_rq, &fair_sched_class))
12985 pulled_task = -1;
12986
12987 out:
12988 /* Move the next balance forward */
12989 if (time_after(this_rq->next_balance, next_balance))
12990 this_rq->next_balance = next_balance;
12991
12992 if (pulled_task)
12993 this_rq->idle_stamp = 0;
12994 else
12995 nohz_newidle_balance(this_rq);
12996
12997 rq_repin_lock(this_rq, rf);
12998
12999 return pulled_task;
13000 }
13001
13002 /*
13003 * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
13004 *
13005 * - directly from the local sched_tick() for periodic load balancing
13006 *
13007 * - indirectly from a remote sched_tick() for NOHZ idle balancing
13008 * through the SMP cross-call nohz_csd_func()
13009 */
sched_balance_softirq(void)13010 static __latent_entropy void sched_balance_softirq(void)
13011 {
13012 struct rq *this_rq = this_rq();
13013 enum cpu_idle_type idle = this_rq->idle_balance;
13014 /*
13015 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
13016 * balancing on behalf of the other idle CPUs whose ticks are
13017 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
13018 * give the idle CPUs a chance to load balance. Else we may
13019 * load balance only within the local sched_domain hierarchy
13020 * and abort nohz_idle_balance altogether if we pull some load.
13021 */
13022 if (nohz_idle_balance(this_rq, idle))
13023 return;
13024
13025 /* normal load balance */
13026 sched_balance_update_blocked_averages(this_rq->cpu);
13027 sched_balance_domains(this_rq, idle);
13028 }
13029
13030 /*
13031 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
13032 */
sched_balance_trigger(struct rq * rq)13033 void sched_balance_trigger(struct rq *rq)
13034 {
13035 /*
13036 * Don't need to rebalance while attached to NULL domain or
13037 * runqueue CPU is not active
13038 */
13039 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
13040 return;
13041
13042 if (time_after_eq(jiffies, rq->next_balance))
13043 raise_softirq(SCHED_SOFTIRQ);
13044
13045 nohz_balancer_kick(rq);
13046 }
13047
rq_online_fair(struct rq * rq)13048 static void rq_online_fair(struct rq *rq)
13049 {
13050 update_sysctl();
13051
13052 update_runtime_enabled(rq);
13053 }
13054
rq_offline_fair(struct rq * rq)13055 static void rq_offline_fair(struct rq *rq)
13056 {
13057 update_sysctl();
13058
13059 /* Ensure any throttled groups are reachable by pick_next_task */
13060 unthrottle_offline_cfs_rqs(rq);
13061
13062 /* Ensure that we remove rq contribution to group share: */
13063 clear_tg_offline_cfs_rqs(rq);
13064 }
13065
13066 #ifdef CONFIG_SCHED_CORE
13067 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)13068 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13069 {
13070 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13071 u64 slice = se->slice;
13072
13073 return (rtime * min_nr_tasks > slice);
13074 }
13075
13076 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
task_tick_core(struct rq * rq,struct task_struct * curr)13077 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13078 {
13079 if (!sched_core_enabled(rq))
13080 return;
13081
13082 /*
13083 * If runqueue has only one task which used up its slice and
13084 * if the sibling is forced idle, then trigger schedule to
13085 * give forced idle task a chance.
13086 *
13087 * sched_slice() considers only this active rq and it gets the
13088 * whole slice. But during force idle, we have siblings acting
13089 * like a single runqueue and hence we need to consider runnable
13090 * tasks on this CPU and the forced idle CPU. Ideally, we should
13091 * go through the forced idle rq, but that would be a perf hit.
13092 * We can assume that the forced idle CPU has at least
13093 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13094 * if we need to give up the CPU.
13095 */
13096 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 &&
13097 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13098 resched_curr(rq);
13099 }
13100
13101 /*
13102 * Consider any infeasible weight scenario. Take for instance two tasks,
13103 * each bound to their respective sibling, one with weight 1 and one with
13104 * weight 2. Then the lower weight task will run ahead of the higher weight
13105 * task without bound.
13106 *
13107 * This utterly destroys the concept of a shared time base.
13108 *
13109 * Remember; all this is about a proportionally fair scheduling, where each
13110 * tasks receives:
13111 *
13112 * w_i
13113 * dt_i = ---------- dt (1)
13114 * \Sum_j w_j
13115 *
13116 * which we do by tracking a virtual time, s_i:
13117 *
13118 * 1
13119 * s_i = --- d[t]_i (2)
13120 * w_i
13121 *
13122 * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
13123 * The immediate corollary is that the ideal schedule S, where (2) to use
13124 * an infinitesimal delta, is:
13125 *
13126 * 1
13127 * S = ---------- dt (3)
13128 * \Sum_i w_i
13129 *
13130 * From which we can define the lag, or deviation from the ideal, as:
13131 *
13132 * lag(i) = S - s_i (4)
13133 *
13134 * And since the one and only purpose is to approximate S, we get that:
13135 *
13136 * \Sum_i w_i lag(i) := 0 (5)
13137 *
13138 * If this were not so, we no longer converge to S, and we can no longer
13139 * claim our scheduler has any of the properties we derive from S. This is
13140 * exactly what you did above, you broke it!
13141 *
13142 *
13143 * Let's continue for a while though; to see if there is anything useful to
13144 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
13145 *
13146 * \Sum_i w_i s_i
13147 * S = -------------- (6)
13148 * \Sum_i w_i
13149 *
13150 * Which gives us a way to compute S, given our s_i. Now, if you've read
13151 * our code, you know that we do not in fact do this, the reason for this
13152 * is two-fold. Firstly, computing S in that way requires a 64bit division
13153 * for every time we'd use it (see 12), and secondly, this only describes
13154 * the steady-state, it doesn't handle dynamics.
13155 *
13156 * Anyway, in (6): s_i -> x + (s_i - x), to get:
13157 *
13158 * \Sum_i w_i (s_i - x)
13159 * S - x = -------------------- (7)
13160 * \Sum_i w_i
13161 *
13162 * Which shows that S and s_i transform alike (which makes perfect sense
13163 * given that S is basically the (weighted) average of s_i).
13164 *
13165 * So the thing to remember is that the above is strictly UP. It is
13166 * possible to generalize to multiple runqueues -- however it gets really
13167 * yuck when you have to add affinity support, as illustrated by our very
13168 * first counter-example.
13169 *
13170 * Luckily I think we can avoid needing a full multi-queue variant for
13171 * core-scheduling (or load-balancing). The crucial observation is that we
13172 * only actually need this comparison in the presence of forced-idle; only
13173 * then do we need to tell if the stalled rq has higher priority over the
13174 * other.
13175 *
13176 * [XXX assumes SMT2; better consider the more general case, I suspect
13177 * it'll work out because our comparison is always between 2 rqs and the
13178 * answer is only interesting if one of them is forced-idle]
13179 *
13180 * And (under assumption of SMT2) when there is forced-idle, there is only
13181 * a single queue, so everything works like normal.
13182 *
13183 * Let, for our runqueue 'k':
13184 *
13185 * T_k = \Sum_i w_i s_i
13186 * W_k = \Sum_i w_i ; for all i of k (8)
13187 *
13188 * Then we can write (6) like:
13189 *
13190 * T_k
13191 * S_k = --- (9)
13192 * W_k
13193 *
13194 * From which immediately follows that:
13195 *
13196 * T_k + T_l
13197 * S_k+l = --------- (10)
13198 * W_k + W_l
13199 *
13200 * On which we can define a combined lag:
13201 *
13202 * lag_k+l(i) := S_k+l - s_i (11)
13203 *
13204 * And that gives us the tools to compare tasks across a combined runqueue.
13205 *
13206 *
13207 * Combined this gives the following:
13208 *
13209 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
13210 * using (7); this only requires storing single 'time'-stamps.
13211 *
13212 * b) when comparing tasks between 2 runqueues of which one is forced-idle,
13213 * compare the combined lag, per (11).
13214 *
13215 * Now, of course cgroups (I so hate them) make this more interesting in
13216 * that a) seems to suggest we need to iterate all cgroup on a CPU at such
13217 * boundaries, but I think we can avoid that. The force-idle is for the
13218 * whole CPU, all it's rqs. So we can mark it in the root and lazily
13219 * propagate downward on demand.
13220 */
13221
13222 /*
13223 * So this sync is basically a relative reset of S to 0.
13224 *
13225 * So with 2 queues, when one goes idle, we drop them both to 0 and one
13226 * then increases due to not being idle, and the idle one builds up lag to
13227 * get re-elected. So far so simple, right?
13228 *
13229 * When there's 3, we can have the situation where 2 run and one is idle,
13230 * we sync to 0 and let the idle one build up lag to get re-election. Now
13231 * suppose another one also drops idle. At this point dropping all to 0
13232 * again would destroy the built-up lag from the queue that was already
13233 * idle, not good.
13234 *
13235 * So instead of syncing everything, we can:
13236 *
13237 * less := !((s64)(s_a - s_b) <= 0)
13238 *
13239 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
13240 * == v_a - (v_b - S_a + S_b)
13241 *
13242 * IOW, we can recast the (lag) comparison to a one-sided difference.
13243 * So if then, instead of syncing the whole queue, sync the idle queue
13244 * against the active queue with S_a + S_b at the point where we sync.
13245 *
13246 * (XXX consider the implication of living in a cyclic group: N / 2^n N)
13247 *
13248 * This gives us means of syncing single queues against the active queue,
13249 * and for already idle queues to preserve their build-up lag.
13250 *
13251 * Of course, then we get the situation where there's 2 active and one
13252 * going idle, who do we pick to sync against? Theory would have us sync
13253 * against the combined S, but as we've already demonstrated, there is no
13254 * such thing in infeasible weight scenarios.
13255 *
13256 * One thing I've considered; and this is where that core_active rudiment
13257 * came from, is having active queues sync up between themselves after
13258 * every tick. This limits the observed divergence due to the work
13259 * conservancy.
13260 *
13261 * On top of that, we can improve upon things by employing (10) here.
13262 */
13263
13264 /*
13265 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
13266 */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)13267 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13268 bool forceidle)
13269 {
13270 for_each_sched_entity(se) {
13271 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13272
13273 if (forceidle) {
13274 if (cfs_rq->forceidle_seq == fi_seq)
13275 break;
13276 cfs_rq->forceidle_seq = fi_seq;
13277 }
13278
13279 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
13280 }
13281 }
13282
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13283 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13284 {
13285 struct sched_entity *se = &p->se;
13286
13287 if (p->sched_class != &fair_sched_class)
13288 return;
13289
13290 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13291 }
13292
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13293 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13294 bool in_fi)
13295 {
13296 struct rq *rq = task_rq(a);
13297 const struct sched_entity *sea = &a->se;
13298 const struct sched_entity *seb = &b->se;
13299 struct cfs_rq *cfs_rqa;
13300 struct cfs_rq *cfs_rqb;
13301 s64 delta;
13302
13303 WARN_ON_ONCE(task_rq(b)->core != rq->core);
13304
13305 #ifdef CONFIG_FAIR_GROUP_SCHED
13306 /*
13307 * Find an se in the hierarchy for tasks a and b, such that the se's
13308 * are immediate siblings.
13309 */
13310 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13311 int sea_depth = sea->depth;
13312 int seb_depth = seb->depth;
13313
13314 if (sea_depth >= seb_depth)
13315 sea = parent_entity(sea);
13316 if (sea_depth <= seb_depth)
13317 seb = parent_entity(seb);
13318 }
13319
13320 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13321 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13322
13323 cfs_rqa = sea->cfs_rq;
13324 cfs_rqb = seb->cfs_rq;
13325 #else /* !CONFIG_FAIR_GROUP_SCHED: */
13326 cfs_rqa = &task_rq(a)->cfs;
13327 cfs_rqb = &task_rq(b)->cfs;
13328 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13329
13330 /*
13331 * Find delta after normalizing se's vruntime with its cfs_rq's
13332 * zero_vruntime_fi, which would have been updated in prior calls
13333 * to se_fi_update().
13334 */
13335 delta = (s64)(sea->vruntime - seb->vruntime) +
13336 (s64)(cfs_rqb->zero_vruntime_fi - cfs_rqa->zero_vruntime_fi);
13337
13338 return delta > 0;
13339 }
13340
task_is_throttled_fair(struct task_struct * p,int cpu)13341 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13342 {
13343 struct cfs_rq *cfs_rq;
13344
13345 #ifdef CONFIG_FAIR_GROUP_SCHED
13346 cfs_rq = task_group(p)->cfs_rq[cpu];
13347 #else
13348 cfs_rq = &cpu_rq(cpu)->cfs;
13349 #endif
13350 return throttled_hierarchy(cfs_rq);
13351 }
13352 #else /* !CONFIG_SCHED_CORE: */
task_tick_core(struct rq * rq,struct task_struct * curr)13353 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13354 #endif /* !CONFIG_SCHED_CORE */
13355
13356 /*
13357 * scheduler tick hitting a task of our scheduling class.
13358 *
13359 * NOTE: This function can be called remotely by the tick offload that
13360 * goes along full dynticks. Therefore no local assumption can be made
13361 * and everything must be accessed through the @rq and @curr passed in
13362 * parameters.
13363 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13364 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13365 {
13366 struct cfs_rq *cfs_rq;
13367 struct sched_entity *se = &curr->se;
13368
13369 for_each_sched_entity(se) {
13370 cfs_rq = cfs_rq_of(se);
13371 entity_tick(cfs_rq, se, queued);
13372 }
13373
13374 if (static_branch_unlikely(&sched_numa_balancing))
13375 task_tick_numa(rq, curr);
13376
13377 update_misfit_status(curr, rq);
13378 check_update_overutilized_status(task_rq(curr));
13379
13380 task_tick_core(rq, curr);
13381 }
13382
13383 /*
13384 * called on fork with the child task as argument from the parent's context
13385 * - child not yet on the tasklist
13386 * - preemption disabled
13387 */
task_fork_fair(struct task_struct * p)13388 static void task_fork_fair(struct task_struct *p)
13389 {
13390 set_task_max_allowed_capacity(p);
13391 }
13392
13393 /*
13394 * Priority of the task has changed. Check to see if we preempt
13395 * the current task.
13396 */
13397 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,u64 oldprio)13398 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
13399 {
13400 if (!task_on_rq_queued(p))
13401 return;
13402
13403 if (p->prio == oldprio)
13404 return;
13405
13406 if (rq->cfs.nr_queued == 1)
13407 return;
13408
13409 /*
13410 * Reschedule if we are currently running on this runqueue and
13411 * our priority decreased, or if we are not currently running on
13412 * this runqueue and our priority is higher than the current's
13413 */
13414 if (task_current_donor(rq, p)) {
13415 if (p->prio > oldprio)
13416 resched_curr(rq);
13417 } else {
13418 wakeup_preempt(rq, p, 0);
13419 }
13420 }
13421
13422 #ifdef CONFIG_FAIR_GROUP_SCHED
13423 /*
13424 * Propagate the changes of the sched_entity across the tg tree to make it
13425 * visible to the root
13426 */
propagate_entity_cfs_rq(struct sched_entity * se)13427 static void propagate_entity_cfs_rq(struct sched_entity *se)
13428 {
13429 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13430
13431 /*
13432 * If a task gets attached to this cfs_rq and before being queued,
13433 * it gets migrated to another CPU due to reasons like affinity
13434 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
13435 * that removed load decayed or it can cause faireness problem.
13436 */
13437 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13438 list_add_leaf_cfs_rq(cfs_rq);
13439
13440 /* Start to propagate at parent */
13441 se = se->parent;
13442
13443 for_each_sched_entity(se) {
13444 cfs_rq = cfs_rq_of(se);
13445
13446 update_load_avg(cfs_rq, se, UPDATE_TG);
13447
13448 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13449 list_add_leaf_cfs_rq(cfs_rq);
13450 }
13451
13452 assert_list_leaf_cfs_rq(rq_of(cfs_rq));
13453 }
13454 #else /* !CONFIG_FAIR_GROUP_SCHED: */
propagate_entity_cfs_rq(struct sched_entity * se)13455 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13456 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13457
detach_entity_cfs_rq(struct sched_entity * se)13458 static void detach_entity_cfs_rq(struct sched_entity *se)
13459 {
13460 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13461
13462 /*
13463 * In case the task sched_avg hasn't been attached:
13464 * - A forked task which hasn't been woken up by wake_up_new_task().
13465 * - A task which has been woken up by try_to_wake_up() but is
13466 * waiting for actually being woken up by sched_ttwu_pending().
13467 */
13468 if (!se->avg.last_update_time)
13469 return;
13470
13471 /* Catch up with the cfs_rq and remove our load when we leave */
13472 update_load_avg(cfs_rq, se, 0);
13473 detach_entity_load_avg(cfs_rq, se);
13474 update_tg_load_avg(cfs_rq);
13475 propagate_entity_cfs_rq(se);
13476 }
13477
attach_entity_cfs_rq(struct sched_entity * se)13478 static void attach_entity_cfs_rq(struct sched_entity *se)
13479 {
13480 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13481
13482 /* Synchronize entity with its cfs_rq */
13483 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13484 attach_entity_load_avg(cfs_rq, se);
13485 update_tg_load_avg(cfs_rq);
13486 propagate_entity_cfs_rq(se);
13487 }
13488
detach_task_cfs_rq(struct task_struct * p)13489 static void detach_task_cfs_rq(struct task_struct *p)
13490 {
13491 struct sched_entity *se = &p->se;
13492
13493 detach_entity_cfs_rq(se);
13494 }
13495
attach_task_cfs_rq(struct task_struct * p)13496 static void attach_task_cfs_rq(struct task_struct *p)
13497 {
13498 struct sched_entity *se = &p->se;
13499
13500 attach_entity_cfs_rq(se);
13501 }
13502
switching_from_fair(struct rq * rq,struct task_struct * p)13503 static void switching_from_fair(struct rq *rq, struct task_struct *p)
13504 {
13505 if (p->se.sched_delayed)
13506 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
13507 }
13508
switched_from_fair(struct rq * rq,struct task_struct * p)13509 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13510 {
13511 detach_task_cfs_rq(p);
13512 }
13513
switched_to_fair(struct rq * rq,struct task_struct * p)13514 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13515 {
13516 WARN_ON_ONCE(p->se.sched_delayed);
13517
13518 attach_task_cfs_rq(p);
13519
13520 set_task_max_allowed_capacity(p);
13521
13522 if (task_on_rq_queued(p)) {
13523 /*
13524 * We were most likely switched from sched_rt, so
13525 * kick off the schedule if running, otherwise just see
13526 * if we can still preempt the current task.
13527 */
13528 if (task_current_donor(rq, p))
13529 resched_curr(rq);
13530 else
13531 wakeup_preempt(rq, p, 0);
13532 }
13533 }
13534
__set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13535 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13536 {
13537 struct sched_entity *se = &p->se;
13538
13539 if (task_on_rq_queued(p)) {
13540 /*
13541 * Move the next running task to the front of the list, so our
13542 * cfs_tasks list becomes MRU one.
13543 */
13544 list_move(&se->group_node, &rq->cfs_tasks);
13545 }
13546 if (!first)
13547 return;
13548
13549 WARN_ON_ONCE(se->sched_delayed);
13550
13551 if (hrtick_enabled_fair(rq))
13552 hrtick_start_fair(rq, p);
13553
13554 update_misfit_status(p, rq);
13555 sched_fair_update_stop_tick(rq, p);
13556 }
13557
13558 /*
13559 * Account for a task changing its policy or group.
13560 *
13561 * This routine is mostly called to set cfs_rq->curr field when a task
13562 * migrates between groups/classes.
13563 */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13564 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13565 {
13566 struct sched_entity *se = &p->se;
13567
13568 for_each_sched_entity(se) {
13569 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13570
13571 set_next_entity(cfs_rq, se);
13572 /* ensure bandwidth has been allocated on our new cfs_rq */
13573 account_cfs_rq_runtime(cfs_rq, 0);
13574 }
13575
13576 __set_next_task_fair(rq, p, first);
13577 }
13578
init_cfs_rq(struct cfs_rq * cfs_rq)13579 void init_cfs_rq(struct cfs_rq *cfs_rq)
13580 {
13581 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13582 cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
13583 raw_spin_lock_init(&cfs_rq->removed.lock);
13584 }
13585
13586 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13587 static void task_change_group_fair(struct task_struct *p)
13588 {
13589 /*
13590 * We couldn't detach or attach a forked task which
13591 * hasn't been woken up by wake_up_new_task().
13592 */
13593 if (READ_ONCE(p->__state) == TASK_NEW)
13594 return;
13595
13596 detach_task_cfs_rq(p);
13597
13598 /* Tell se's cfs_rq has been changed -- migrated */
13599 p->se.avg.last_update_time = 0;
13600 set_task_rq(p, task_cpu(p));
13601 attach_task_cfs_rq(p);
13602 }
13603
free_fair_sched_group(struct task_group * tg)13604 void free_fair_sched_group(struct task_group *tg)
13605 {
13606 int i;
13607
13608 for_each_possible_cpu(i) {
13609 if (tg->cfs_rq)
13610 kfree(tg->cfs_rq[i]);
13611 if (tg->se)
13612 kfree(tg->se[i]);
13613 }
13614
13615 kfree(tg->cfs_rq);
13616 kfree(tg->se);
13617 }
13618
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13619 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13620 {
13621 struct sched_entity *se;
13622 struct cfs_rq *cfs_rq;
13623 int i;
13624
13625 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13626 if (!tg->cfs_rq)
13627 goto err;
13628 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13629 if (!tg->se)
13630 goto err;
13631
13632 tg->shares = NICE_0_LOAD;
13633
13634 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13635
13636 for_each_possible_cpu(i) {
13637 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13638 GFP_KERNEL, cpu_to_node(i));
13639 if (!cfs_rq)
13640 goto err;
13641
13642 se = kzalloc_node(sizeof(struct sched_entity_stats),
13643 GFP_KERNEL, cpu_to_node(i));
13644 if (!se)
13645 goto err_free_rq;
13646
13647 init_cfs_rq(cfs_rq);
13648 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13649 init_entity_runnable_average(se);
13650 }
13651
13652 return 1;
13653
13654 err_free_rq:
13655 kfree(cfs_rq);
13656 err:
13657 return 0;
13658 }
13659
online_fair_sched_group(struct task_group * tg)13660 void online_fair_sched_group(struct task_group *tg)
13661 {
13662 struct sched_entity *se;
13663 struct rq_flags rf;
13664 struct rq *rq;
13665 int i;
13666
13667 for_each_possible_cpu(i) {
13668 rq = cpu_rq(i);
13669 se = tg->se[i];
13670 rq_lock_irq(rq, &rf);
13671 update_rq_clock(rq);
13672 attach_entity_cfs_rq(se);
13673 sync_throttle(tg, i);
13674 rq_unlock_irq(rq, &rf);
13675 }
13676 }
13677
unregister_fair_sched_group(struct task_group * tg)13678 void unregister_fair_sched_group(struct task_group *tg)
13679 {
13680 int cpu;
13681
13682 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13683
13684 for_each_possible_cpu(cpu) {
13685 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13686 struct sched_entity *se = tg->se[cpu];
13687 struct rq *rq = cpu_rq(cpu);
13688
13689 if (se) {
13690 if (se->sched_delayed) {
13691 guard(rq_lock_irqsave)(rq);
13692 if (se->sched_delayed) {
13693 update_rq_clock(rq);
13694 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13695 }
13696 list_del_leaf_cfs_rq(cfs_rq);
13697 }
13698 remove_entity_load_avg(se);
13699 }
13700
13701 /*
13702 * Only empty task groups can be destroyed; so we can speculatively
13703 * check on_list without danger of it being re-added.
13704 */
13705 if (cfs_rq->on_list) {
13706 guard(rq_lock_irqsave)(rq);
13707 list_del_leaf_cfs_rq(cfs_rq);
13708 }
13709 }
13710 }
13711
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)13712 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13713 struct sched_entity *se, int cpu,
13714 struct sched_entity *parent)
13715 {
13716 struct rq *rq = cpu_rq(cpu);
13717
13718 cfs_rq->tg = tg;
13719 cfs_rq->rq = rq;
13720 init_cfs_rq_runtime(cfs_rq);
13721
13722 tg->cfs_rq[cpu] = cfs_rq;
13723 tg->se[cpu] = se;
13724
13725 /* se could be NULL for root_task_group */
13726 if (!se)
13727 return;
13728
13729 if (!parent) {
13730 se->cfs_rq = &rq->cfs;
13731 se->depth = 0;
13732 } else {
13733 se->cfs_rq = parent->my_q;
13734 se->depth = parent->depth + 1;
13735 }
13736
13737 se->my_q = cfs_rq;
13738 /* guarantee group entities always have weight */
13739 update_load_set(&se->load, NICE_0_LOAD);
13740 se->parent = parent;
13741 }
13742
13743 static DEFINE_MUTEX(shares_mutex);
13744
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13745 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13746 {
13747 int i;
13748
13749 lockdep_assert_held(&shares_mutex);
13750
13751 /*
13752 * We can't change the weight of the root cgroup.
13753 */
13754 if (!tg->se[0])
13755 return -EINVAL;
13756
13757 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13758
13759 if (tg->shares == shares)
13760 return 0;
13761
13762 tg->shares = shares;
13763 for_each_possible_cpu(i) {
13764 struct rq *rq = cpu_rq(i);
13765 struct sched_entity *se = tg->se[i];
13766 struct rq_flags rf;
13767
13768 /* Propagate contribution to hierarchy */
13769 rq_lock_irqsave(rq, &rf);
13770 update_rq_clock(rq);
13771 for_each_sched_entity(se) {
13772 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13773 update_cfs_group(se);
13774 }
13775 rq_unlock_irqrestore(rq, &rf);
13776 }
13777
13778 return 0;
13779 }
13780
sched_group_set_shares(struct task_group * tg,unsigned long shares)13781 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13782 {
13783 int ret;
13784
13785 mutex_lock(&shares_mutex);
13786 if (tg_is_idle(tg))
13787 ret = -EINVAL;
13788 else
13789 ret = __sched_group_set_shares(tg, shares);
13790 mutex_unlock(&shares_mutex);
13791
13792 return ret;
13793 }
13794
sched_group_set_idle(struct task_group * tg,long idle)13795 int sched_group_set_idle(struct task_group *tg, long idle)
13796 {
13797 int i;
13798
13799 if (tg == &root_task_group)
13800 return -EINVAL;
13801
13802 if (idle < 0 || idle > 1)
13803 return -EINVAL;
13804
13805 mutex_lock(&shares_mutex);
13806
13807 if (tg->idle == idle) {
13808 mutex_unlock(&shares_mutex);
13809 return 0;
13810 }
13811
13812 tg->idle = idle;
13813
13814 for_each_possible_cpu(i) {
13815 struct rq *rq = cpu_rq(i);
13816 struct sched_entity *se = tg->se[i];
13817 struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i];
13818 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13819 long idle_task_delta;
13820 struct rq_flags rf;
13821
13822 rq_lock_irqsave(rq, &rf);
13823
13824 grp_cfs_rq->idle = idle;
13825 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13826 goto next_cpu;
13827
13828 idle_task_delta = grp_cfs_rq->h_nr_queued -
13829 grp_cfs_rq->h_nr_idle;
13830 if (!cfs_rq_is_idle(grp_cfs_rq))
13831 idle_task_delta *= -1;
13832
13833 for_each_sched_entity(se) {
13834 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13835
13836 if (!se->on_rq)
13837 break;
13838
13839 cfs_rq->h_nr_idle += idle_task_delta;
13840
13841 /* Already accounted at parent level and above. */
13842 if (cfs_rq_is_idle(cfs_rq))
13843 break;
13844 }
13845
13846 next_cpu:
13847 rq_unlock_irqrestore(rq, &rf);
13848 }
13849
13850 /* Idle groups have minimum weight. */
13851 if (tg_is_idle(tg))
13852 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13853 else
13854 __sched_group_set_shares(tg, NICE_0_LOAD);
13855
13856 mutex_unlock(&shares_mutex);
13857 return 0;
13858 }
13859
13860 #endif /* CONFIG_FAIR_GROUP_SCHED */
13861
13862
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13863 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13864 {
13865 struct sched_entity *se = &task->se;
13866 unsigned int rr_interval = 0;
13867
13868 /*
13869 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13870 * idle runqueue:
13871 */
13872 if (rq->cfs.load.weight)
13873 rr_interval = NS_TO_JIFFIES(se->slice);
13874
13875 return rr_interval;
13876 }
13877
13878 /*
13879 * All the scheduling class methods:
13880 */
13881 DEFINE_SCHED_CLASS(fair) = {
13882
13883 .queue_mask = 2,
13884
13885 .enqueue_task = enqueue_task_fair,
13886 .dequeue_task = dequeue_task_fair,
13887 .yield_task = yield_task_fair,
13888 .yield_to_task = yield_to_task_fair,
13889
13890 .wakeup_preempt = check_preempt_wakeup_fair,
13891
13892 .pick_task = pick_task_fair,
13893 .pick_next_task = pick_next_task_fair,
13894 .put_prev_task = put_prev_task_fair,
13895 .set_next_task = set_next_task_fair,
13896
13897 .select_task_rq = select_task_rq_fair,
13898 .migrate_task_rq = migrate_task_rq_fair,
13899
13900 .rq_online = rq_online_fair,
13901 .rq_offline = rq_offline_fair,
13902
13903 .task_dead = task_dead_fair,
13904 .set_cpus_allowed = set_cpus_allowed_fair,
13905
13906 .task_tick = task_tick_fair,
13907 .task_fork = task_fork_fair,
13908
13909 .reweight_task = reweight_task_fair,
13910 .prio_changed = prio_changed_fair,
13911 .switching_from = switching_from_fair,
13912 .switched_from = switched_from_fair,
13913 .switched_to = switched_to_fair,
13914
13915 .get_rr_interval = get_rr_interval_fair,
13916
13917 .update_curr = update_curr_fair,
13918
13919 #ifdef CONFIG_FAIR_GROUP_SCHED
13920 .task_change_group = task_change_group_fair,
13921 #endif
13922
13923 #ifdef CONFIG_SCHED_CORE
13924 .task_is_throttled = task_is_throttled_fair,
13925 #endif
13926
13927 #ifdef CONFIG_UCLAMP_TASK
13928 .uclamp_enabled = 1,
13929 #endif
13930 };
13931
print_cfs_stats(struct seq_file * m,int cpu)13932 void print_cfs_stats(struct seq_file *m, int cpu)
13933 {
13934 struct cfs_rq *cfs_rq, *pos;
13935
13936 rcu_read_lock();
13937 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13938 print_cfs_rq(m, cpu, cfs_rq);
13939 rcu_read_unlock();
13940 }
13941
13942 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13943 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13944 {
13945 int node;
13946 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13947 struct numa_group *ng;
13948
13949 rcu_read_lock();
13950 ng = rcu_dereference(p->numa_group);
13951 for_each_online_node(node) {
13952 if (p->numa_faults) {
13953 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13954 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13955 }
13956 if (ng) {
13957 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13958 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13959 }
13960 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13961 }
13962 rcu_read_unlock();
13963 }
13964 #endif /* CONFIG_NUMA_BALANCING */
13965
init_sched_fair_class(void)13966 __init void init_sched_fair_class(void)
13967 {
13968 int i;
13969
13970 for_each_possible_cpu(i) {
13971 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13972 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
13973 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13974 GFP_KERNEL, cpu_to_node(i));
13975
13976 #ifdef CONFIG_CFS_BANDWIDTH
13977 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13978 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13979 #endif
13980 }
13981
13982 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
13983
13984 #ifdef CONFIG_NO_HZ_COMMON
13985 nohz.next_balance = jiffies;
13986 nohz.next_blocked = jiffies;
13987 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13988 #endif
13989 }
13990