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 if (cfs_rq->tg_load_avg_contrib)
4038 return false;
4039
4040 return true;
4041 }
4042
4043 /**
4044 * update_tg_load_avg - update the tg's load avg
4045 * @cfs_rq: the cfs_rq whose avg changed
4046 *
4047 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4048 * However, because tg->load_avg is a global value there are performance
4049 * considerations.
4050 *
4051 * In order to avoid having to look at the other cfs_rq's, we use a
4052 * differential update where we store the last value we propagated. This in
4053 * turn allows skipping updates if the differential is 'small'.
4054 *
4055 * Updating tg's load_avg is necessary before update_cfs_share().
4056 */
update_tg_load_avg(struct cfs_rq * cfs_rq)4057 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4058 {
4059 long delta;
4060 u64 now;
4061
4062 /*
4063 * No need to update load_avg for root_task_group as it is not used.
4064 */
4065 if (cfs_rq->tg == &root_task_group)
4066 return;
4067
4068 /* rq has been offline and doesn't contribute to the share anymore: */
4069 if (!cpu_active(cpu_of(rq_of(cfs_rq))))
4070 return;
4071
4072 /*
4073 * For migration heavy workloads, access to tg->load_avg can be
4074 * unbound. Limit the update rate to at most once per ms.
4075 */
4076 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4077 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC)
4078 return;
4079
4080 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4081 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4082 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4083 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4084 cfs_rq->last_update_tg_load_avg = now;
4085 }
4086 }
4087
clear_tg_load_avg(struct cfs_rq * cfs_rq)4088 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq)
4089 {
4090 long delta;
4091 u64 now;
4092
4093 /*
4094 * No need to update load_avg for root_task_group, as it is not used.
4095 */
4096 if (cfs_rq->tg == &root_task_group)
4097 return;
4098
4099 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq)));
4100 delta = 0 - cfs_rq->tg_load_avg_contrib;
4101 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4102 cfs_rq->tg_load_avg_contrib = 0;
4103 cfs_rq->last_update_tg_load_avg = now;
4104 }
4105
4106 /* CPU offline callback: */
clear_tg_offline_cfs_rqs(struct rq * rq)4107 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq)
4108 {
4109 struct task_group *tg;
4110
4111 lockdep_assert_rq_held(rq);
4112
4113 /*
4114 * The rq clock has already been updated in
4115 * set_rq_offline(), so we should skip updating
4116 * the rq clock again in unthrottle_cfs_rq().
4117 */
4118 rq_clock_start_loop_update(rq);
4119
4120 rcu_read_lock();
4121 list_for_each_entry_rcu(tg, &task_groups, list) {
4122 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4123
4124 clear_tg_load_avg(cfs_rq);
4125 }
4126 rcu_read_unlock();
4127
4128 rq_clock_stop_loop_update(rq);
4129 }
4130
4131 /*
4132 * Called within set_task_rq() right before setting a task's CPU. The
4133 * caller only guarantees p->pi_lock is held; no other assumptions,
4134 * including the state of rq->lock, should be made.
4135 */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4136 void set_task_rq_fair(struct sched_entity *se,
4137 struct cfs_rq *prev, struct cfs_rq *next)
4138 {
4139 u64 p_last_update_time;
4140 u64 n_last_update_time;
4141
4142 if (!sched_feat(ATTACH_AGE_LOAD))
4143 return;
4144
4145 /*
4146 * We are supposed to update the task to "current" time, then its up to
4147 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4148 * getting what current time is, so simply throw away the out-of-date
4149 * time. This will result in the wakee task is less decayed, but giving
4150 * the wakee more load sounds not bad.
4151 */
4152 if (!(se->avg.last_update_time && prev))
4153 return;
4154
4155 p_last_update_time = cfs_rq_last_update_time(prev);
4156 n_last_update_time = cfs_rq_last_update_time(next);
4157
4158 __update_load_avg_blocked_se(p_last_update_time, se);
4159 se->avg.last_update_time = n_last_update_time;
4160 }
4161
4162 /*
4163 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4164 * propagate its contribution. The key to this propagation is the invariant
4165 * that for each group:
4166 *
4167 * ge->avg == grq->avg (1)
4168 *
4169 * _IFF_ we look at the pure running and runnable sums. Because they
4170 * represent the very same entity, just at different points in the hierarchy.
4171 *
4172 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4173 * and simply copies the running/runnable sum over (but still wrong, because
4174 * the group entity and group rq do not have their PELT windows aligned).
4175 *
4176 * However, update_tg_cfs_load() is more complex. So we have:
4177 *
4178 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4179 *
4180 * And since, like util, the runnable part should be directly transferable,
4181 * the following would _appear_ to be the straight forward approach:
4182 *
4183 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4184 *
4185 * And per (1) we have:
4186 *
4187 * ge->avg.runnable_avg == grq->avg.runnable_avg
4188 *
4189 * Which gives:
4190 *
4191 * ge->load.weight * grq->avg.load_avg
4192 * ge->avg.load_avg = ----------------------------------- (4)
4193 * grq->load.weight
4194 *
4195 * Except that is wrong!
4196 *
4197 * Because while for entities historical weight is not important and we
4198 * really only care about our future and therefore can consider a pure
4199 * runnable sum, runqueues can NOT do this.
4200 *
4201 * We specifically want runqueues to have a load_avg that includes
4202 * historical weights. Those represent the blocked load, the load we expect
4203 * to (shortly) return to us. This only works by keeping the weights as
4204 * integral part of the sum. We therefore cannot decompose as per (3).
4205 *
4206 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4207 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4208 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4209 * runnable section of these tasks overlap (or not). If they were to perfectly
4210 * align the rq as a whole would be runnable 2/3 of the time. If however we
4211 * always have at least 1 runnable task, the rq as a whole is always runnable.
4212 *
4213 * So we'll have to approximate.. :/
4214 *
4215 * Given the constraint:
4216 *
4217 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4218 *
4219 * We can construct a rule that adds runnable to a rq by assuming minimal
4220 * overlap.
4221 *
4222 * On removal, we'll assume each task is equally runnable; which yields:
4223 *
4224 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4225 *
4226 * XXX: only do this for the part of runnable > running ?
4227 *
4228 */
4229 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4230 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4231 {
4232 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4233 u32 new_sum, divider;
4234
4235 /* Nothing to update */
4236 if (!delta_avg)
4237 return;
4238
4239 /*
4240 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4241 * See ___update_load_avg() for details.
4242 */
4243 divider = get_pelt_divider(&cfs_rq->avg);
4244
4245
4246 /* Set new sched_entity's utilization */
4247 se->avg.util_avg = gcfs_rq->avg.util_avg;
4248 new_sum = se->avg.util_avg * divider;
4249 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4250 se->avg.util_sum = new_sum;
4251
4252 /* Update parent cfs_rq utilization */
4253 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4254 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4255
4256 /* See update_cfs_rq_load_avg() */
4257 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4258 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4259 }
4260
4261 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4262 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4263 {
4264 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4265 u32 new_sum, divider;
4266
4267 /* Nothing to update */
4268 if (!delta_avg)
4269 return;
4270
4271 /*
4272 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4273 * See ___update_load_avg() for details.
4274 */
4275 divider = get_pelt_divider(&cfs_rq->avg);
4276
4277 /* Set new sched_entity's runnable */
4278 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4279 new_sum = se->avg.runnable_avg * divider;
4280 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4281 se->avg.runnable_sum = new_sum;
4282
4283 /* Update parent cfs_rq runnable */
4284 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4285 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4286 /* See update_cfs_rq_load_avg() */
4287 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4288 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4289 }
4290
4291 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4292 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4293 {
4294 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4295 unsigned long load_avg;
4296 u64 load_sum = 0;
4297 s64 delta_sum;
4298 u32 divider;
4299
4300 if (!runnable_sum)
4301 return;
4302
4303 gcfs_rq->prop_runnable_sum = 0;
4304
4305 /*
4306 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4307 * See ___update_load_avg() for details.
4308 */
4309 divider = get_pelt_divider(&cfs_rq->avg);
4310
4311 if (runnable_sum >= 0) {
4312 /*
4313 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4314 * the CPU is saturated running == runnable.
4315 */
4316 runnable_sum += se->avg.load_sum;
4317 runnable_sum = min_t(long, runnable_sum, divider);
4318 } else {
4319 /*
4320 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4321 * assuming all tasks are equally runnable.
4322 */
4323 if (scale_load_down(gcfs_rq->load.weight)) {
4324 load_sum = div_u64(gcfs_rq->avg.load_sum,
4325 scale_load_down(gcfs_rq->load.weight));
4326 }
4327
4328 /* But make sure to not inflate se's runnable */
4329 runnable_sum = min(se->avg.load_sum, load_sum);
4330 }
4331
4332 /*
4333 * runnable_sum can't be lower than running_sum
4334 * Rescale running sum to be in the same range as runnable sum
4335 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4336 * runnable_sum is in [0 : LOAD_AVG_MAX]
4337 */
4338 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4339 runnable_sum = max(runnable_sum, running_sum);
4340
4341 load_sum = se_weight(se) * runnable_sum;
4342 load_avg = div_u64(load_sum, divider);
4343
4344 delta_avg = load_avg - se->avg.load_avg;
4345 if (!delta_avg)
4346 return;
4347
4348 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4349
4350 se->avg.load_sum = runnable_sum;
4351 se->avg.load_avg = load_avg;
4352 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4353 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4354 /* See update_cfs_rq_load_avg() */
4355 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4356 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4357 }
4358
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4359 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4360 {
4361 cfs_rq->propagate = 1;
4362 cfs_rq->prop_runnable_sum += runnable_sum;
4363 }
4364
4365 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4366 static inline int propagate_entity_load_avg(struct sched_entity *se)
4367 {
4368 struct cfs_rq *cfs_rq, *gcfs_rq;
4369
4370 if (entity_is_task(se))
4371 return 0;
4372
4373 gcfs_rq = group_cfs_rq(se);
4374 if (!gcfs_rq->propagate)
4375 return 0;
4376
4377 gcfs_rq->propagate = 0;
4378
4379 cfs_rq = cfs_rq_of(se);
4380
4381 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4382
4383 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4384 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4385 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4386
4387 trace_pelt_cfs_tp(cfs_rq);
4388 trace_pelt_se_tp(se);
4389
4390 return 1;
4391 }
4392
4393 /*
4394 * Check if we need to update the load and the utilization of a blocked
4395 * group_entity:
4396 */
skip_blocked_update(struct sched_entity * se)4397 static inline bool skip_blocked_update(struct sched_entity *se)
4398 {
4399 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4400
4401 /*
4402 * If sched_entity still have not zero load or utilization, we have to
4403 * decay it:
4404 */
4405 if (se->avg.load_avg || se->avg.util_avg)
4406 return false;
4407
4408 /*
4409 * If there is a pending propagation, we have to update the load and
4410 * the utilization of the sched_entity:
4411 */
4412 if (gcfs_rq->propagate)
4413 return false;
4414
4415 /*
4416 * Otherwise, the load and the utilization of the sched_entity is
4417 * already zero and there is no pending propagation, so it will be a
4418 * waste of time to try to decay it:
4419 */
4420 return true;
4421 }
4422
4423 #else /* !CONFIG_FAIR_GROUP_SCHED: */
4424
update_tg_load_avg(struct cfs_rq * cfs_rq)4425 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4426
clear_tg_offline_cfs_rqs(struct rq * rq)4427 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {}
4428
propagate_entity_load_avg(struct sched_entity * se)4429 static inline int propagate_entity_load_avg(struct sched_entity *se)
4430 {
4431 return 0;
4432 }
4433
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4434 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4435
4436 #endif /* !CONFIG_FAIR_GROUP_SCHED */
4437
4438 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4439 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4440 {
4441 u64 throttled = 0, now, lut;
4442 struct cfs_rq *cfs_rq;
4443 struct rq *rq;
4444 bool is_idle;
4445
4446 if (load_avg_is_decayed(&se->avg))
4447 return;
4448
4449 cfs_rq = cfs_rq_of(se);
4450 rq = rq_of(cfs_rq);
4451
4452 rcu_read_lock();
4453 is_idle = is_idle_task(rcu_dereference(rq->curr));
4454 rcu_read_unlock();
4455
4456 /*
4457 * The lag estimation comes with a cost we don't want to pay all the
4458 * time. Hence, limiting to the case where the source CPU is idle and
4459 * we know we are at the greatest risk to have an outdated clock.
4460 */
4461 if (!is_idle)
4462 return;
4463
4464 /*
4465 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4466 *
4467 * last_update_time (the cfs_rq's last_update_time)
4468 * = cfs_rq_clock_pelt()@cfs_rq_idle
4469 * = rq_clock_pelt()@cfs_rq_idle
4470 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4471 *
4472 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4473 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4474 *
4475 * rq_idle_lag (delta between now and rq's update)
4476 * = sched_clock_cpu() - rq_clock()@rq_idle
4477 *
4478 * We can then write:
4479 *
4480 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4481 * sched_clock_cpu() - rq_clock()@rq_idle
4482 * Where:
4483 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4484 * rq_clock()@rq_idle is rq->clock_idle
4485 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4486 * is cfs_rq->throttled_pelt_idle
4487 */
4488
4489 #ifdef CONFIG_CFS_BANDWIDTH
4490 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4491 /* The clock has been stopped for throttling */
4492 if (throttled == U64_MAX)
4493 return;
4494 #endif
4495 now = u64_u32_load(rq->clock_pelt_idle);
4496 /*
4497 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4498 * is observed the old clock_pelt_idle value and the new clock_idle,
4499 * which lead to an underestimation. The opposite would lead to an
4500 * overestimation.
4501 */
4502 smp_rmb();
4503 lut = cfs_rq_last_update_time(cfs_rq);
4504
4505 now -= throttled;
4506 if (now < lut)
4507 /*
4508 * cfs_rq->avg.last_update_time is more recent than our
4509 * estimation, let's use it.
4510 */
4511 now = lut;
4512 else
4513 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4514
4515 __update_load_avg_blocked_se(now, se);
4516 }
4517 #else /* !CONFIG_NO_HZ_COMMON: */
migrate_se_pelt_lag(struct sched_entity * se)4518 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4519 #endif /* !CONFIG_NO_HZ_COMMON */
4520
4521 /**
4522 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4523 * @now: current time, as per cfs_rq_clock_pelt()
4524 * @cfs_rq: cfs_rq to update
4525 *
4526 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4527 * avg. The immediate corollary is that all (fair) tasks must be attached.
4528 *
4529 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4530 *
4531 * Return: true if the load decayed or we removed load.
4532 *
4533 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4534 * call update_tg_load_avg() when this function returns true.
4535 */
4536 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4537 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4538 {
4539 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4540 struct sched_avg *sa = &cfs_rq->avg;
4541 int decayed = 0;
4542
4543 if (cfs_rq->removed.nr) {
4544 unsigned long r;
4545 u32 divider = get_pelt_divider(&cfs_rq->avg);
4546
4547 raw_spin_lock(&cfs_rq->removed.lock);
4548 swap(cfs_rq->removed.util_avg, removed_util);
4549 swap(cfs_rq->removed.load_avg, removed_load);
4550 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4551 cfs_rq->removed.nr = 0;
4552 raw_spin_unlock(&cfs_rq->removed.lock);
4553
4554 r = removed_load;
4555 sub_positive(&sa->load_avg, r);
4556 sub_positive(&sa->load_sum, r * divider);
4557 /* See sa->util_sum below */
4558 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4559
4560 r = removed_util;
4561 sub_positive(&sa->util_avg, r);
4562 sub_positive(&sa->util_sum, r * divider);
4563 /*
4564 * Because of rounding, se->util_sum might ends up being +1 more than
4565 * cfs->util_sum. Although this is not a problem by itself, detaching
4566 * a lot of tasks with the rounding problem between 2 updates of
4567 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4568 * cfs_util_avg is not.
4569 * Check that util_sum is still above its lower bound for the new
4570 * util_avg. Given that period_contrib might have moved since the last
4571 * sync, we are only sure that util_sum must be above or equal to
4572 * util_avg * minimum possible divider
4573 */
4574 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4575
4576 r = removed_runnable;
4577 sub_positive(&sa->runnable_avg, r);
4578 sub_positive(&sa->runnable_sum, r * divider);
4579 /* See sa->util_sum above */
4580 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4581 sa->runnable_avg * PELT_MIN_DIVIDER);
4582
4583 /*
4584 * removed_runnable is the unweighted version of removed_load so we
4585 * can use it to estimate removed_load_sum.
4586 */
4587 add_tg_cfs_propagate(cfs_rq,
4588 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4589
4590 decayed = 1;
4591 }
4592
4593 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4594 u64_u32_store_copy(sa->last_update_time,
4595 cfs_rq->last_update_time_copy,
4596 sa->last_update_time);
4597 return decayed;
4598 }
4599
4600 /**
4601 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4602 * @cfs_rq: cfs_rq to attach to
4603 * @se: sched_entity to attach
4604 *
4605 * Must call update_cfs_rq_load_avg() before this, since we rely on
4606 * cfs_rq->avg.last_update_time being current.
4607 */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4608 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4609 {
4610 /*
4611 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4612 * See ___update_load_avg() for details.
4613 */
4614 u32 divider = get_pelt_divider(&cfs_rq->avg);
4615
4616 /*
4617 * When we attach the @se to the @cfs_rq, we must align the decay
4618 * window because without that, really weird and wonderful things can
4619 * happen.
4620 *
4621 * XXX illustrate
4622 */
4623 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4624 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4625
4626 /*
4627 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4628 * period_contrib. This isn't strictly correct, but since we're
4629 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4630 * _sum a little.
4631 */
4632 se->avg.util_sum = se->avg.util_avg * divider;
4633
4634 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4635
4636 se->avg.load_sum = se->avg.load_avg * divider;
4637 if (se_weight(se) < se->avg.load_sum)
4638 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4639 else
4640 se->avg.load_sum = 1;
4641
4642 enqueue_load_avg(cfs_rq, se);
4643 cfs_rq->avg.util_avg += se->avg.util_avg;
4644 cfs_rq->avg.util_sum += se->avg.util_sum;
4645 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4646 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4647
4648 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4649
4650 cfs_rq_util_change(cfs_rq, 0);
4651
4652 trace_pelt_cfs_tp(cfs_rq);
4653 }
4654
4655 /**
4656 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4657 * @cfs_rq: cfs_rq to detach from
4658 * @se: sched_entity to detach
4659 *
4660 * Must call update_cfs_rq_load_avg() before this, since we rely on
4661 * cfs_rq->avg.last_update_time being current.
4662 */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4663 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4664 {
4665 dequeue_load_avg(cfs_rq, se);
4666 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4667 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4668 /* See update_cfs_rq_load_avg() */
4669 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4670 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4671
4672 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4673 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4674 /* See update_cfs_rq_load_avg() */
4675 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4676 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4677
4678 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4679
4680 cfs_rq_util_change(cfs_rq, 0);
4681
4682 trace_pelt_cfs_tp(cfs_rq);
4683 }
4684
4685 /*
4686 * Optional action to be done while updating the load average
4687 */
4688 #define UPDATE_TG 0x1
4689 #define SKIP_AGE_LOAD 0x2
4690 #define DO_ATTACH 0x4
4691 #define DO_DETACH 0x8
4692
4693 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4694 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4695 {
4696 u64 now = cfs_rq_clock_pelt(cfs_rq);
4697 int decayed;
4698
4699 /*
4700 * Track task load average for carrying it to new CPU after migrated, and
4701 * track group sched_entity load average for task_h_load calculation in migration
4702 */
4703 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4704 __update_load_avg_se(now, cfs_rq, se);
4705
4706 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4707 decayed |= propagate_entity_load_avg(se);
4708
4709 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4710
4711 /*
4712 * DO_ATTACH means we're here from enqueue_entity().
4713 * !last_update_time means we've passed through
4714 * migrate_task_rq_fair() indicating we migrated.
4715 *
4716 * IOW we're enqueueing a task on a new CPU.
4717 */
4718 attach_entity_load_avg(cfs_rq, se);
4719 update_tg_load_avg(cfs_rq);
4720
4721 } else if (flags & DO_DETACH) {
4722 /*
4723 * DO_DETACH means we're here from dequeue_entity()
4724 * and we are migrating task out of the CPU.
4725 */
4726 detach_entity_load_avg(cfs_rq, se);
4727 update_tg_load_avg(cfs_rq);
4728 } else if (decayed) {
4729 cfs_rq_util_change(cfs_rq, 0);
4730
4731 if (flags & UPDATE_TG)
4732 update_tg_load_avg(cfs_rq);
4733 }
4734 }
4735
4736 /*
4737 * Synchronize entity load avg of dequeued entity without locking
4738 * the previous rq.
4739 */
sync_entity_load_avg(struct sched_entity * se)4740 static void sync_entity_load_avg(struct sched_entity *se)
4741 {
4742 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4743 u64 last_update_time;
4744
4745 last_update_time = cfs_rq_last_update_time(cfs_rq);
4746 __update_load_avg_blocked_se(last_update_time, se);
4747 }
4748
4749 /*
4750 * Task first catches up with cfs_rq, and then subtract
4751 * itself from the cfs_rq (task must be off the queue now).
4752 */
remove_entity_load_avg(struct sched_entity * se)4753 static void remove_entity_load_avg(struct sched_entity *se)
4754 {
4755 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4756 unsigned long flags;
4757
4758 /*
4759 * tasks cannot exit without having gone through wake_up_new_task() ->
4760 * enqueue_task_fair() which will have added things to the cfs_rq,
4761 * so we can remove unconditionally.
4762 */
4763
4764 sync_entity_load_avg(se);
4765
4766 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4767 ++cfs_rq->removed.nr;
4768 cfs_rq->removed.util_avg += se->avg.util_avg;
4769 cfs_rq->removed.load_avg += se->avg.load_avg;
4770 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4771 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4772 }
4773
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4774 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4775 {
4776 return cfs_rq->avg.runnable_avg;
4777 }
4778
cfs_rq_load_avg(struct cfs_rq * cfs_rq)4779 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4780 {
4781 return cfs_rq->avg.load_avg;
4782 }
4783
4784 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf);
4785
task_util(struct task_struct * p)4786 static inline unsigned long task_util(struct task_struct *p)
4787 {
4788 return READ_ONCE(p->se.avg.util_avg);
4789 }
4790
task_runnable(struct task_struct * p)4791 static inline unsigned long task_runnable(struct task_struct *p)
4792 {
4793 return READ_ONCE(p->se.avg.runnable_avg);
4794 }
4795
_task_util_est(struct task_struct * p)4796 static inline unsigned long _task_util_est(struct task_struct *p)
4797 {
4798 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED;
4799 }
4800
task_util_est(struct task_struct * p)4801 static inline unsigned long task_util_est(struct task_struct *p)
4802 {
4803 return max(task_util(p), _task_util_est(p));
4804 }
4805
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4806 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4807 struct task_struct *p)
4808 {
4809 unsigned int enqueued;
4810
4811 if (!sched_feat(UTIL_EST))
4812 return;
4813
4814 /* Update root cfs_rq's estimated utilization */
4815 enqueued = cfs_rq->avg.util_est;
4816 enqueued += _task_util_est(p);
4817 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4818
4819 trace_sched_util_est_cfs_tp(cfs_rq);
4820 }
4821
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4822 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4823 struct task_struct *p)
4824 {
4825 unsigned int enqueued;
4826
4827 if (!sched_feat(UTIL_EST))
4828 return;
4829
4830 /* Update root cfs_rq's estimated utilization */
4831 enqueued = cfs_rq->avg.util_est;
4832 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4833 WRITE_ONCE(cfs_rq->avg.util_est, enqueued);
4834
4835 trace_sched_util_est_cfs_tp(cfs_rq);
4836 }
4837
4838 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4839
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4840 static inline void util_est_update(struct cfs_rq *cfs_rq,
4841 struct task_struct *p,
4842 bool task_sleep)
4843 {
4844 unsigned int ewma, dequeued, last_ewma_diff;
4845
4846 if (!sched_feat(UTIL_EST))
4847 return;
4848
4849 /*
4850 * Skip update of task's estimated utilization when the task has not
4851 * yet completed an activation, e.g. being migrated.
4852 */
4853 if (!task_sleep)
4854 return;
4855
4856 /* Get current estimate of utilization */
4857 ewma = READ_ONCE(p->se.avg.util_est);
4858
4859 /*
4860 * If the PELT values haven't changed since enqueue time,
4861 * skip the util_est update.
4862 */
4863 if (ewma & UTIL_AVG_UNCHANGED)
4864 return;
4865
4866 /* Get utilization at dequeue */
4867 dequeued = task_util(p);
4868
4869 /*
4870 * Reset EWMA on utilization increases, the moving average is used only
4871 * to smooth utilization decreases.
4872 */
4873 if (ewma <= dequeued) {
4874 ewma = dequeued;
4875 goto done;
4876 }
4877
4878 /*
4879 * Skip update of task's estimated utilization when its members are
4880 * already ~1% close to its last activation value.
4881 */
4882 last_ewma_diff = ewma - dequeued;
4883 if (last_ewma_diff < UTIL_EST_MARGIN)
4884 goto done;
4885
4886 /*
4887 * To avoid underestimate of task utilization, skip updates of EWMA if
4888 * we cannot grant that thread got all CPU time it wanted.
4889 */
4890 if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p))
4891 goto done;
4892
4893
4894 /*
4895 * Update Task's estimated utilization
4896 *
4897 * When *p completes an activation we can consolidate another sample
4898 * of the task size. This is done by using this value to update the
4899 * Exponential Weighted Moving Average (EWMA):
4900 *
4901 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4902 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4903 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4904 * = w * ( -last_ewma_diff ) + ewma(t-1)
4905 * = w * (-last_ewma_diff + ewma(t-1) / w)
4906 *
4907 * Where 'w' is the weight of new samples, which is configured to be
4908 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4909 */
4910 ewma <<= UTIL_EST_WEIGHT_SHIFT;
4911 ewma -= last_ewma_diff;
4912 ewma >>= UTIL_EST_WEIGHT_SHIFT;
4913 done:
4914 ewma |= UTIL_AVG_UNCHANGED;
4915 WRITE_ONCE(p->se.avg.util_est, ewma);
4916
4917 trace_sched_util_est_se_tp(&p->se);
4918 }
4919
get_actual_cpu_capacity(int cpu)4920 static inline unsigned long get_actual_cpu_capacity(int cpu)
4921 {
4922 unsigned long capacity = arch_scale_cpu_capacity(cpu);
4923
4924 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu));
4925
4926 return capacity;
4927 }
4928
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)4929 static inline int util_fits_cpu(unsigned long util,
4930 unsigned long uclamp_min,
4931 unsigned long uclamp_max,
4932 int cpu)
4933 {
4934 unsigned long capacity = capacity_of(cpu);
4935 unsigned long capacity_orig;
4936 bool fits, uclamp_max_fits;
4937
4938 /*
4939 * Check if the real util fits without any uclamp boost/cap applied.
4940 */
4941 fits = fits_capacity(util, capacity);
4942
4943 if (!uclamp_is_used())
4944 return fits;
4945
4946 /*
4947 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and
4948 * uclamp_max. We only care about capacity pressure (by using
4949 * capacity_of()) for comparing against the real util.
4950 *
4951 * If a task is boosted to 1024 for example, we don't want a tiny
4952 * pressure to skew the check whether it fits a CPU or not.
4953 *
4954 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it
4955 * should fit a little cpu even if there's some pressure.
4956 *
4957 * Only exception is for HW or cpufreq pressure since it has a direct impact
4958 * on available OPP of the system.
4959 *
4960 * We honour it for uclamp_min only as a drop in performance level
4961 * could result in not getting the requested minimum performance level.
4962 *
4963 * For uclamp_max, we can tolerate a drop in performance level as the
4964 * goal is to cap the task. So it's okay if it's getting less.
4965 */
4966 capacity_orig = arch_scale_cpu_capacity(cpu);
4967
4968 /*
4969 * We want to force a task to fit a cpu as implied by uclamp_max.
4970 * But we do have some corner cases to cater for..
4971 *
4972 *
4973 * C=z
4974 * | ___
4975 * | C=y | |
4976 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4977 * | C=x | | | |
4978 * | ___ | | | |
4979 * | | | | | | | (util somewhere in this region)
4980 * | | | | | | |
4981 * | | | | | | |
4982 * +----------------------------------------
4983 * CPU0 CPU1 CPU2
4984 *
4985 * In the above example if a task is capped to a specific performance
4986 * point, y, then when:
4987 *
4988 * * util = 80% of x then it does not fit on CPU0 and should migrate
4989 * to CPU1
4990 * * util = 80% of y then it is forced to fit on CPU1 to honour
4991 * uclamp_max request.
4992 *
4993 * which is what we're enforcing here. A task always fits if
4994 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4995 * the normal upmigration rules should withhold still.
4996 *
4997 * Only exception is when we are on max capacity, then we need to be
4998 * careful not to block overutilized state. This is so because:
4999 *
5000 * 1. There's no concept of capping at max_capacity! We can't go
5001 * beyond this performance level anyway.
5002 * 2. The system is being saturated when we're operating near
5003 * max capacity, it doesn't make sense to block overutilized.
5004 */
5005 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
5006 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
5007 fits = fits || uclamp_max_fits;
5008
5009 /*
5010 *
5011 * C=z
5012 * | ___ (region a, capped, util >= uclamp_max)
5013 * | C=y | |
5014 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
5015 * | C=x | | | |
5016 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
5017 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
5018 * | | | | | | |
5019 * | | | | | | | (region c, boosted, util < uclamp_min)
5020 * +----------------------------------------
5021 * CPU0 CPU1 CPU2
5022 *
5023 * a) If util > uclamp_max, then we're capped, we don't care about
5024 * actual fitness value here. We only care if uclamp_max fits
5025 * capacity without taking margin/pressure into account.
5026 * See comment above.
5027 *
5028 * b) If uclamp_min <= util <= uclamp_max, then the normal
5029 * fits_capacity() rules apply. Except we need to ensure that we
5030 * enforce we remain within uclamp_max, see comment above.
5031 *
5032 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5033 * need to take into account the boosted value fits the CPU without
5034 * taking margin/pressure into account.
5035 *
5036 * Cases (a) and (b) are handled in the 'fits' variable already. We
5037 * just need to consider an extra check for case (c) after ensuring we
5038 * handle the case uclamp_min > uclamp_max.
5039 */
5040 uclamp_min = min(uclamp_min, uclamp_max);
5041 if (fits && (util < uclamp_min) &&
5042 (uclamp_min > get_actual_cpu_capacity(cpu)))
5043 return -1;
5044
5045 return fits;
5046 }
5047
task_fits_cpu(struct task_struct * p,int cpu)5048 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5049 {
5050 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5051 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5052 unsigned long util = task_util_est(p);
5053 /*
5054 * Return true only if the cpu fully fits the task requirements, which
5055 * include the utilization but also the performance hints.
5056 */
5057 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5058 }
5059
update_misfit_status(struct task_struct * p,struct rq * rq)5060 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5061 {
5062 int cpu = cpu_of(rq);
5063
5064 if (!sched_asym_cpucap_active())
5065 return;
5066
5067 /*
5068 * Affinity allows us to go somewhere higher? Or are we on biggest
5069 * available CPU already? Or do we fit into this CPU ?
5070 */
5071 if (!p || (p->nr_cpus_allowed == 1) ||
5072 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) ||
5073 task_fits_cpu(p, cpu)) {
5074
5075 rq->misfit_task_load = 0;
5076 return;
5077 }
5078
5079 /*
5080 * Make sure that misfit_task_load will not be null even if
5081 * task_h_load() returns 0.
5082 */
5083 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5084 }
5085
__setparam_fair(struct task_struct * p,const struct sched_attr * attr)5086 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr)
5087 {
5088 struct sched_entity *se = &p->se;
5089
5090 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5091 if (attr->sched_runtime) {
5092 se->custom_slice = 1;
5093 se->slice = clamp_t(u64, attr->sched_runtime,
5094 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */
5095 NSEC_PER_MSEC*100); /* HZ=100 / 10 */
5096 } else {
5097 se->custom_slice = 0;
5098 se->slice = sysctl_sched_base_slice;
5099 }
5100 }
5101
5102 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5103 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5104 {
5105 u64 vslice, vruntime = avg_vruntime(cfs_rq);
5106 s64 lag = 0;
5107
5108 if (!se->custom_slice)
5109 se->slice = sysctl_sched_base_slice;
5110 vslice = calc_delta_fair(se->slice, se);
5111
5112 /*
5113 * Due to how V is constructed as the weighted average of entities,
5114 * adding tasks with positive lag, or removing tasks with negative lag
5115 * will move 'time' backwards, this can screw around with the lag of
5116 * other tasks.
5117 *
5118 * EEVDF: placement strategy #1 / #2
5119 */
5120 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) {
5121 struct sched_entity *curr = cfs_rq->curr;
5122 unsigned long load;
5123
5124 lag = se->vlag;
5125
5126 /*
5127 * If we want to place a task and preserve lag, we have to
5128 * consider the effect of the new entity on the weighted
5129 * average and compensate for this, otherwise lag can quickly
5130 * evaporate.
5131 *
5132 * Lag is defined as:
5133 *
5134 * lag_i = S - s_i = w_i * (V - v_i)
5135 *
5136 * To avoid the 'w_i' term all over the place, we only track
5137 * the virtual lag:
5138 *
5139 * vl_i = V - v_i <=> v_i = V - vl_i
5140 *
5141 * And we take V to be the weighted average of all v:
5142 *
5143 * V = (\Sum w_j*v_j) / W
5144 *
5145 * Where W is: \Sum w_j
5146 *
5147 * Then, the weighted average after adding an entity with lag
5148 * vl_i is given by:
5149 *
5150 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5151 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5152 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5153 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i)
5154 * = V - w_i*vl_i / (W + w_i)
5155 *
5156 * And the actual lag after adding an entity with vl_i is:
5157 *
5158 * vl'_i = V' - v_i
5159 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5160 * = vl_i - w_i*vl_i / (W + w_i)
5161 *
5162 * Which is strictly less than vl_i. So in order to preserve lag
5163 * we should inflate the lag before placement such that the
5164 * effective lag after placement comes out right.
5165 *
5166 * As such, invert the above relation for vl'_i to get the vl_i
5167 * we need to use such that the lag after placement is the lag
5168 * we computed before dequeue.
5169 *
5170 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5171 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5172 *
5173 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5174 * = W*vl_i
5175 *
5176 * vl_i = (W + w_i)*vl'_i / W
5177 */
5178 load = cfs_rq->avg_load;
5179 if (curr && curr->on_rq)
5180 load += scale_load_down(curr->load.weight);
5181
5182 lag *= load + scale_load_down(se->load.weight);
5183 if (WARN_ON_ONCE(!load))
5184 load = 1;
5185 lag = div_s64(lag, load);
5186 }
5187
5188 se->vruntime = vruntime - lag;
5189
5190 if (se->rel_deadline) {
5191 se->deadline += se->vruntime;
5192 se->rel_deadline = 0;
5193 return;
5194 }
5195
5196 /*
5197 * When joining the competition; the existing tasks will be,
5198 * on average, halfway through their slice, as such start tasks
5199 * off with half a slice to ease into the competition.
5200 */
5201 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5202 vslice /= 2;
5203
5204 /*
5205 * EEVDF: vd_i = ve_i + r_i/w_i
5206 */
5207 se->deadline = se->vruntime + vslice;
5208 }
5209
5210 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5211 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5212
5213 static void
5214 requeue_delayed_entity(struct sched_entity *se);
5215
5216 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5217 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5218 {
5219 bool curr = cfs_rq->curr == se;
5220
5221 /*
5222 * If we're the current task, we must renormalise before calling
5223 * update_curr().
5224 */
5225 if (curr)
5226 place_entity(cfs_rq, se, flags);
5227
5228 update_curr(cfs_rq);
5229
5230 /*
5231 * When enqueuing a sched_entity, we must:
5232 * - Update loads to have both entity and cfs_rq synced with now.
5233 * - For group_entity, update its runnable_weight to reflect the new
5234 * h_nr_runnable of its group cfs_rq.
5235 * - For group_entity, update its weight to reflect the new share of
5236 * its group cfs_rq
5237 * - Add its new weight to cfs_rq->load.weight
5238 */
5239 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5240 se_update_runnable(se);
5241 /*
5242 * XXX update_load_avg() above will have attached us to the pelt sum;
5243 * but update_cfs_group() here will re-adjust the weight and have to
5244 * undo/redo all that. Seems wasteful.
5245 */
5246 update_cfs_group(se);
5247
5248 /*
5249 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5250 * we can place the entity.
5251 */
5252 if (!curr)
5253 place_entity(cfs_rq, se, flags);
5254
5255 account_entity_enqueue(cfs_rq, se);
5256
5257 /* Entity has migrated, no longer consider this task hot */
5258 if (flags & ENQUEUE_MIGRATED)
5259 se->exec_start = 0;
5260
5261 check_schedstat_required();
5262 update_stats_enqueue_fair(cfs_rq, se, flags);
5263 if (!curr)
5264 __enqueue_entity(cfs_rq, se);
5265 se->on_rq = 1;
5266
5267 if (cfs_rq->nr_queued == 1) {
5268 check_enqueue_throttle(cfs_rq);
5269 list_add_leaf_cfs_rq(cfs_rq);
5270 #ifdef CONFIG_CFS_BANDWIDTH
5271 if (cfs_rq->pelt_clock_throttled) {
5272 struct rq *rq = rq_of(cfs_rq);
5273
5274 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5275 cfs_rq->throttled_clock_pelt;
5276 cfs_rq->pelt_clock_throttled = 0;
5277 }
5278 #endif
5279 }
5280 }
5281
__clear_buddies_next(struct sched_entity * se)5282 static void __clear_buddies_next(struct sched_entity *se)
5283 {
5284 for_each_sched_entity(se) {
5285 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5286 if (cfs_rq->next != se)
5287 break;
5288
5289 cfs_rq->next = NULL;
5290 }
5291 }
5292
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5293 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5294 {
5295 if (cfs_rq->next == se)
5296 __clear_buddies_next(se);
5297 }
5298
5299 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5300
set_delayed(struct sched_entity * se)5301 static void set_delayed(struct sched_entity *se)
5302 {
5303 se->sched_delayed = 1;
5304
5305 /*
5306 * Delayed se of cfs_rq have no tasks queued on them.
5307 * Do not adjust h_nr_runnable since dequeue_entities()
5308 * will account it for blocked tasks.
5309 */
5310 if (!entity_is_task(se))
5311 return;
5312
5313 for_each_sched_entity(se) {
5314 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5315
5316 cfs_rq->h_nr_runnable--;
5317 }
5318 }
5319
clear_delayed(struct sched_entity * se)5320 static void clear_delayed(struct sched_entity *se)
5321 {
5322 se->sched_delayed = 0;
5323
5324 /*
5325 * Delayed se of cfs_rq have no tasks queued on them.
5326 * Do not adjust h_nr_runnable since a dequeue has
5327 * already accounted for it or an enqueue of a task
5328 * below it will account for it in enqueue_task_fair().
5329 */
5330 if (!entity_is_task(se))
5331 return;
5332
5333 for_each_sched_entity(se) {
5334 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5335
5336 cfs_rq->h_nr_runnable++;
5337 }
5338 }
5339
finish_delayed_dequeue_entity(struct sched_entity * se)5340 static inline void finish_delayed_dequeue_entity(struct sched_entity *se)
5341 {
5342 clear_delayed(se);
5343 if (sched_feat(DELAY_ZERO) && se->vlag > 0)
5344 se->vlag = 0;
5345 }
5346
5347 static bool
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5348 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5349 {
5350 bool sleep = flags & DEQUEUE_SLEEP;
5351 int action = UPDATE_TG;
5352
5353 update_curr(cfs_rq);
5354 clear_buddies(cfs_rq, se);
5355
5356 if (flags & DEQUEUE_DELAYED) {
5357 WARN_ON_ONCE(!se->sched_delayed);
5358 } else {
5359 bool delay = sleep;
5360 /*
5361 * DELAY_DEQUEUE relies on spurious wakeups, special task
5362 * states must not suffer spurious wakeups, excempt them.
5363 */
5364 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE))
5365 delay = false;
5366
5367 WARN_ON_ONCE(delay && se->sched_delayed);
5368
5369 if (sched_feat(DELAY_DEQUEUE) && delay &&
5370 !entity_eligible(cfs_rq, se)) {
5371 update_load_avg(cfs_rq, se, 0);
5372 set_delayed(se);
5373 return false;
5374 }
5375 }
5376
5377 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5378 action |= DO_DETACH;
5379
5380 /*
5381 * When dequeuing a sched_entity, we must:
5382 * - Update loads to have both entity and cfs_rq synced with now.
5383 * - For group_entity, update its runnable_weight to reflect the new
5384 * h_nr_runnable of its group cfs_rq.
5385 * - Subtract its previous weight from cfs_rq->load.weight.
5386 * - For group entity, update its weight to reflect the new share
5387 * of its group cfs_rq.
5388 */
5389 update_load_avg(cfs_rq, se, action);
5390 se_update_runnable(se);
5391
5392 update_stats_dequeue_fair(cfs_rq, se, flags);
5393
5394 update_entity_lag(cfs_rq, se);
5395 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) {
5396 se->deadline -= se->vruntime;
5397 se->rel_deadline = 1;
5398 }
5399
5400 if (se != cfs_rq->curr)
5401 __dequeue_entity(cfs_rq, se);
5402 se->on_rq = 0;
5403 account_entity_dequeue(cfs_rq, se);
5404
5405 /* return excess runtime on last dequeue */
5406 return_cfs_rq_runtime(cfs_rq);
5407
5408 update_cfs_group(se);
5409
5410 if (flags & DEQUEUE_DELAYED)
5411 finish_delayed_dequeue_entity(se);
5412
5413 if (cfs_rq->nr_queued == 0) {
5414 update_idle_cfs_rq_clock_pelt(cfs_rq);
5415 #ifdef CONFIG_CFS_BANDWIDTH
5416 if (throttled_hierarchy(cfs_rq)) {
5417 struct rq *rq = rq_of(cfs_rq);
5418
5419 list_del_leaf_cfs_rq(cfs_rq);
5420 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5421 cfs_rq->pelt_clock_throttled = 1;
5422 }
5423 #endif
5424 }
5425
5426 return true;
5427 }
5428
5429 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5430 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5431 {
5432 clear_buddies(cfs_rq, se);
5433
5434 /* 'current' is not kept within the tree. */
5435 if (se->on_rq) {
5436 /*
5437 * Any task has to be enqueued before it get to execute on
5438 * a CPU. So account for the time it spent waiting on the
5439 * runqueue.
5440 */
5441 update_stats_wait_end_fair(cfs_rq, se);
5442 __dequeue_entity(cfs_rq, se);
5443 update_load_avg(cfs_rq, se, UPDATE_TG);
5444
5445 set_protect_slice(cfs_rq, se);
5446 }
5447
5448 update_stats_curr_start(cfs_rq, se);
5449 WARN_ON_ONCE(cfs_rq->curr);
5450 cfs_rq->curr = se;
5451
5452 /*
5453 * Track our maximum slice length, if the CPU's load is at
5454 * least twice that of our own weight (i.e. don't track it
5455 * when there are only lesser-weight tasks around):
5456 */
5457 if (schedstat_enabled() &&
5458 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5459 struct sched_statistics *stats;
5460
5461 stats = __schedstats_from_se(se);
5462 __schedstat_set(stats->slice_max,
5463 max((u64)stats->slice_max,
5464 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5465 }
5466
5467 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5468 }
5469
5470 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags);
5471
5472 /*
5473 * Pick the next process, keeping these things in mind, in this order:
5474 * 1) keep things fair between processes/task groups
5475 * 2) pick the "next" process, since someone really wants that to run
5476 * 3) pick the "last" process, for cache locality
5477 * 4) do not run the "skip" process, if something else is available
5478 */
5479 static struct sched_entity *
pick_next_entity(struct rq * rq,struct cfs_rq * cfs_rq)5480 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq)
5481 {
5482 struct sched_entity *se;
5483
5484 se = pick_eevdf(cfs_rq);
5485 if (se->sched_delayed) {
5486 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
5487 /*
5488 * Must not reference @se again, see __block_task().
5489 */
5490 return NULL;
5491 }
5492 return se;
5493 }
5494
5495 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5496
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5497 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5498 {
5499 /*
5500 * If still on the runqueue then deactivate_task()
5501 * was not called and update_curr() has to be done:
5502 */
5503 if (prev->on_rq)
5504 update_curr(cfs_rq);
5505
5506 /* throttle cfs_rqs exceeding runtime */
5507 check_cfs_rq_runtime(cfs_rq);
5508
5509 if (prev->on_rq) {
5510 update_stats_wait_start_fair(cfs_rq, prev);
5511 /* Put 'current' back into the tree. */
5512 __enqueue_entity(cfs_rq, prev);
5513 /* in !on_rq case, update occurred at dequeue */
5514 update_load_avg(cfs_rq, prev, 0);
5515 }
5516 WARN_ON_ONCE(cfs_rq->curr != prev);
5517 cfs_rq->curr = NULL;
5518 }
5519
5520 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5521 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5522 {
5523 /*
5524 * Update run-time statistics of the 'current'.
5525 */
5526 update_curr(cfs_rq);
5527
5528 /*
5529 * Ensure that runnable average is periodically updated.
5530 */
5531 update_load_avg(cfs_rq, curr, UPDATE_TG);
5532 update_cfs_group(curr);
5533
5534 #ifdef CONFIG_SCHED_HRTICK
5535 /*
5536 * queued ticks are scheduled to match the slice, so don't bother
5537 * validating it and just reschedule.
5538 */
5539 if (queued) {
5540 resched_curr_lazy(rq_of(cfs_rq));
5541 return;
5542 }
5543 #endif
5544 }
5545
5546
5547 /**************************************************
5548 * CFS bandwidth control machinery
5549 */
5550
5551 #ifdef CONFIG_CFS_BANDWIDTH
5552
5553 #ifdef CONFIG_JUMP_LABEL
5554 static struct static_key __cfs_bandwidth_used;
5555
cfs_bandwidth_used(void)5556 static inline bool cfs_bandwidth_used(void)
5557 {
5558 return static_key_false(&__cfs_bandwidth_used);
5559 }
5560
cfs_bandwidth_usage_inc(void)5561 void cfs_bandwidth_usage_inc(void)
5562 {
5563 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5564 }
5565
cfs_bandwidth_usage_dec(void)5566 void cfs_bandwidth_usage_dec(void)
5567 {
5568 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5569 }
5570 #else /* !CONFIG_JUMP_LABEL: */
cfs_bandwidth_used(void)5571 static bool cfs_bandwidth_used(void)
5572 {
5573 return true;
5574 }
5575
cfs_bandwidth_usage_inc(void)5576 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5577 void cfs_bandwidth_usage_dec(void) {}
5578 #endif /* !CONFIG_JUMP_LABEL */
5579
sched_cfs_bandwidth_slice(void)5580 static inline u64 sched_cfs_bandwidth_slice(void)
5581 {
5582 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5583 }
5584
5585 /*
5586 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5587 * directly instead of rq->clock to avoid adding additional synchronization
5588 * around rq->lock.
5589 *
5590 * requires cfs_b->lock
5591 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5592 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5593 {
5594 s64 runtime;
5595
5596 if (unlikely(cfs_b->quota == RUNTIME_INF))
5597 return;
5598
5599 cfs_b->runtime += cfs_b->quota;
5600 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5601 if (runtime > 0) {
5602 cfs_b->burst_time += runtime;
5603 cfs_b->nr_burst++;
5604 }
5605
5606 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5607 cfs_b->runtime_snap = cfs_b->runtime;
5608 }
5609
tg_cfs_bandwidth(struct task_group * tg)5610 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5611 {
5612 return &tg->cfs_bandwidth;
5613 }
5614
5615 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5616 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5617 struct cfs_rq *cfs_rq, u64 target_runtime)
5618 {
5619 u64 min_amount, amount = 0;
5620
5621 lockdep_assert_held(&cfs_b->lock);
5622
5623 /* note: this is a positive sum as runtime_remaining <= 0 */
5624 min_amount = target_runtime - cfs_rq->runtime_remaining;
5625
5626 if (cfs_b->quota == RUNTIME_INF)
5627 amount = min_amount;
5628 else {
5629 start_cfs_bandwidth(cfs_b);
5630
5631 if (cfs_b->runtime > 0) {
5632 amount = min(cfs_b->runtime, min_amount);
5633 cfs_b->runtime -= amount;
5634 cfs_b->idle = 0;
5635 }
5636 }
5637
5638 cfs_rq->runtime_remaining += amount;
5639
5640 return cfs_rq->runtime_remaining > 0;
5641 }
5642
5643 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5644 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5645 {
5646 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5647 int ret;
5648
5649 raw_spin_lock(&cfs_b->lock);
5650 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5651 raw_spin_unlock(&cfs_b->lock);
5652
5653 return ret;
5654 }
5655
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5656 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5657 {
5658 /* dock delta_exec before expiring quota (as it could span periods) */
5659 cfs_rq->runtime_remaining -= delta_exec;
5660
5661 if (likely(cfs_rq->runtime_remaining > 0))
5662 return;
5663
5664 if (cfs_rq->throttled)
5665 return;
5666 /*
5667 * if we're unable to extend our runtime we resched so that the active
5668 * hierarchy can be throttled
5669 */
5670 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5671 resched_curr(rq_of(cfs_rq));
5672 }
5673
5674 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5675 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5676 {
5677 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5678 return;
5679
5680 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5681 }
5682
cfs_rq_throttled(struct cfs_rq * cfs_rq)5683 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5684 {
5685 return cfs_bandwidth_used() && cfs_rq->throttled;
5686 }
5687
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)5688 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
5689 {
5690 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled;
5691 }
5692
5693 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5694 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5695 {
5696 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5697 }
5698
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)5699 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
5700 {
5701 return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]);
5702 }
5703
task_is_throttled(struct task_struct * p)5704 static inline bool task_is_throttled(struct task_struct *p)
5705 {
5706 return cfs_bandwidth_used() && p->throttled;
5707 }
5708
5709 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags);
throttle_cfs_rq_work(struct callback_head * work)5710 static void throttle_cfs_rq_work(struct callback_head *work)
5711 {
5712 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work);
5713 struct sched_entity *se;
5714 struct cfs_rq *cfs_rq;
5715 struct rq *rq;
5716
5717 WARN_ON_ONCE(p != current);
5718 p->sched_throttle_work.next = &p->sched_throttle_work;
5719
5720 /*
5721 * If task is exiting, then there won't be a return to userspace, so we
5722 * don't have to bother with any of this.
5723 */
5724 if ((p->flags & PF_EXITING))
5725 return;
5726
5727 scoped_guard(task_rq_lock, p) {
5728 se = &p->se;
5729 cfs_rq = cfs_rq_of(se);
5730
5731 /* Raced, forget */
5732 if (p->sched_class != &fair_sched_class)
5733 return;
5734
5735 /*
5736 * If not in limbo, then either replenish has happened or this
5737 * task got migrated out of the throttled cfs_rq, move along.
5738 */
5739 if (!cfs_rq->throttle_count)
5740 return;
5741 rq = scope.rq;
5742 update_rq_clock(rq);
5743 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node));
5744 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE);
5745 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5746 /*
5747 * Must not set throttled before dequeue or dequeue will
5748 * mistakenly regard this task as an already throttled one.
5749 */
5750 p->throttled = true;
5751 resched_curr(rq);
5752 }
5753 }
5754
init_cfs_throttle_work(struct task_struct * p)5755 void init_cfs_throttle_work(struct task_struct *p)
5756 {
5757 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work);
5758 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */
5759 p->sched_throttle_work.next = &p->sched_throttle_work;
5760 INIT_LIST_HEAD(&p->throttle_node);
5761 }
5762
5763 /*
5764 * Task is throttled and someone wants to dequeue it again:
5765 * it could be sched/core when core needs to do things like
5766 * task affinity change, task group change, task sched class
5767 * change etc. and in these cases, DEQUEUE_SLEEP is not set;
5768 * or the task is blocked after throttled due to freezer etc.
5769 * and in these cases, DEQUEUE_SLEEP is set.
5770 */
5771 static void detach_task_cfs_rq(struct task_struct *p);
dequeue_throttled_task(struct task_struct * p,int flags)5772 static void dequeue_throttled_task(struct task_struct *p, int flags)
5773 {
5774 WARN_ON_ONCE(p->se.on_rq);
5775 list_del_init(&p->throttle_node);
5776
5777 /* task blocked after throttled */
5778 if (flags & DEQUEUE_SLEEP) {
5779 p->throttled = false;
5780 return;
5781 }
5782
5783 /*
5784 * task is migrating off its old cfs_rq, detach
5785 * the task's load from its old cfs_rq.
5786 */
5787 if (task_on_rq_migrating(p))
5788 detach_task_cfs_rq(p);
5789 }
5790
enqueue_throttled_task(struct task_struct * p)5791 static bool enqueue_throttled_task(struct task_struct *p)
5792 {
5793 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se);
5794
5795 /* @p should have gone through dequeue_throttled_task() first */
5796 WARN_ON_ONCE(!list_empty(&p->throttle_node));
5797
5798 /*
5799 * If the throttled task @p is enqueued to a throttled cfs_rq,
5800 * take the fast path by directly putting the task on the
5801 * target cfs_rq's limbo list.
5802 *
5803 * Do not do that when @p is current because the following race can
5804 * cause @p's group_node to be incorectly re-insterted in its rq's
5805 * cfs_tasks list, despite being throttled:
5806 *
5807 * cpuX cpuY
5808 * p ret2user
5809 * throttle_cfs_rq_work() sched_move_task(p)
5810 * LOCK task_rq_lock
5811 * dequeue_task_fair(p)
5812 * UNLOCK task_rq_lock
5813 * LOCK task_rq_lock
5814 * task_current_donor(p) == true
5815 * task_on_rq_queued(p) == true
5816 * dequeue_task(p)
5817 * put_prev_task(p)
5818 * sched_change_group()
5819 * enqueue_task(p) -> p's new cfs_rq
5820 * is throttled, go
5821 * fast path and skip
5822 * actual enqueue
5823 * set_next_task(p)
5824 * list_move(&se->group_node, &rq->cfs_tasks); // bug
5825 * schedule()
5826 *
5827 * In the above race case, @p current cfs_rq is in the same rq as
5828 * its previous cfs_rq because sched_move_task() only moves a task
5829 * to a different group from the same rq, so we can use its current
5830 * cfs_rq to derive rq and test if the task is current.
5831 */
5832 if (throttled_hierarchy(cfs_rq) &&
5833 !task_current_donor(rq_of(cfs_rq), p)) {
5834 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list);
5835 return true;
5836 }
5837
5838 /* we can't take the fast path, do an actual enqueue*/
5839 p->throttled = false;
5840 return false;
5841 }
5842
5843 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags);
tg_unthrottle_up(struct task_group * tg,void * data)5844 static int tg_unthrottle_up(struct task_group *tg, void *data)
5845 {
5846 struct rq *rq = data;
5847 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5848 struct task_struct *p, *tmp;
5849
5850 if (--cfs_rq->throttle_count)
5851 return 0;
5852
5853 if (cfs_rq->pelt_clock_throttled) {
5854 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5855 cfs_rq->throttled_clock_pelt;
5856 cfs_rq->pelt_clock_throttled = 0;
5857 }
5858
5859 if (cfs_rq->throttled_clock_self) {
5860 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5861
5862 cfs_rq->throttled_clock_self = 0;
5863
5864 if (WARN_ON_ONCE((s64)delta < 0))
5865 delta = 0;
5866
5867 cfs_rq->throttled_clock_self_time += delta;
5868 }
5869
5870 /* Re-enqueue the tasks that have been throttled at this level. */
5871 list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) {
5872 list_del_init(&p->throttle_node);
5873 p->throttled = false;
5874 enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP);
5875 }
5876
5877 /* Add cfs_rq with load or one or more already running entities to the list */
5878 if (!cfs_rq_is_decayed(cfs_rq))
5879 list_add_leaf_cfs_rq(cfs_rq);
5880
5881 return 0;
5882 }
5883
task_has_throttle_work(struct task_struct * p)5884 static inline bool task_has_throttle_work(struct task_struct *p)
5885 {
5886 return p->sched_throttle_work.next != &p->sched_throttle_work;
5887 }
5888
task_throttle_setup_work(struct task_struct * p)5889 static inline void task_throttle_setup_work(struct task_struct *p)
5890 {
5891 if (task_has_throttle_work(p))
5892 return;
5893
5894 /*
5895 * Kthreads and exiting tasks don't return to userspace, so adding the
5896 * work is pointless
5897 */
5898 if ((p->flags & (PF_EXITING | PF_KTHREAD)))
5899 return;
5900
5901 task_work_add(p, &p->sched_throttle_work, TWA_RESUME);
5902 }
5903
record_throttle_clock(struct cfs_rq * cfs_rq)5904 static void record_throttle_clock(struct cfs_rq *cfs_rq)
5905 {
5906 struct rq *rq = rq_of(cfs_rq);
5907
5908 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5909 cfs_rq->throttled_clock = rq_clock(rq);
5910
5911 if (!cfs_rq->throttled_clock_self)
5912 cfs_rq->throttled_clock_self = rq_clock(rq);
5913 }
5914
tg_throttle_down(struct task_group * tg,void * data)5915 static int tg_throttle_down(struct task_group *tg, void *data)
5916 {
5917 struct rq *rq = data;
5918 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5919
5920 if (cfs_rq->throttle_count++)
5921 return 0;
5922
5923 /*
5924 * For cfs_rqs that still have entities enqueued, PELT clock
5925 * stop happens at dequeue time when all entities are dequeued.
5926 */
5927 if (!cfs_rq->nr_queued) {
5928 list_del_leaf_cfs_rq(cfs_rq);
5929 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5930 cfs_rq->pelt_clock_throttled = 1;
5931 }
5932
5933 WARN_ON_ONCE(cfs_rq->throttled_clock_self);
5934 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list));
5935 return 0;
5936 }
5937
throttle_cfs_rq(struct cfs_rq * cfs_rq)5938 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5939 {
5940 struct rq *rq = rq_of(cfs_rq);
5941 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5942 int dequeue = 1;
5943
5944 raw_spin_lock(&cfs_b->lock);
5945 /* This will start the period timer if necessary */
5946 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5947 /*
5948 * We have raced with bandwidth becoming available, and if we
5949 * actually throttled the timer might not unthrottle us for an
5950 * entire period. We additionally needed to make sure that any
5951 * subsequent check_cfs_rq_runtime calls agree not to throttle
5952 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5953 * for 1ns of runtime rather than just check cfs_b.
5954 */
5955 dequeue = 0;
5956 } else {
5957 list_add_tail_rcu(&cfs_rq->throttled_list,
5958 &cfs_b->throttled_cfs_rq);
5959 }
5960 raw_spin_unlock(&cfs_b->lock);
5961
5962 if (!dequeue)
5963 return false; /* Throttle no longer required. */
5964
5965 /* freeze hierarchy runnable averages while throttled */
5966 rcu_read_lock();
5967 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5968 rcu_read_unlock();
5969
5970 /*
5971 * Note: distribution will already see us throttled via the
5972 * throttled-list. rq->lock protects completion.
5973 */
5974 cfs_rq->throttled = 1;
5975 WARN_ON_ONCE(cfs_rq->throttled_clock);
5976 return true;
5977 }
5978
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)5979 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5980 {
5981 struct rq *rq = rq_of(cfs_rq);
5982 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5983 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
5984
5985 /*
5986 * It's possible we are called with runtime_remaining < 0 due to things
5987 * like async unthrottled us with a positive runtime_remaining but other
5988 * still running entities consumed those runtime before we reached here.
5989 *
5990 * We can't unthrottle this cfs_rq without any runtime remaining because
5991 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle,
5992 * which is not supposed to happen on unthrottle path.
5993 */
5994 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0)
5995 return;
5996
5997 cfs_rq->throttled = 0;
5998
5999 update_rq_clock(rq);
6000
6001 raw_spin_lock(&cfs_b->lock);
6002 if (cfs_rq->throttled_clock) {
6003 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
6004 cfs_rq->throttled_clock = 0;
6005 }
6006 list_del_rcu(&cfs_rq->throttled_list);
6007 raw_spin_unlock(&cfs_b->lock);
6008
6009 /* update hierarchical throttle state */
6010 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
6011
6012 if (!cfs_rq->load.weight) {
6013 if (!cfs_rq->on_list)
6014 return;
6015 /*
6016 * Nothing to run but something to decay (on_list)?
6017 * Complete the branch.
6018 */
6019 for_each_sched_entity(se) {
6020 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
6021 break;
6022 }
6023 }
6024
6025 assert_list_leaf_cfs_rq(rq);
6026
6027 /* Determine whether we need to wake up potentially idle CPU: */
6028 if (rq->curr == rq->idle && rq->cfs.nr_queued)
6029 resched_curr(rq);
6030 }
6031
__cfsb_csd_unthrottle(void * arg)6032 static void __cfsb_csd_unthrottle(void *arg)
6033 {
6034 struct cfs_rq *cursor, *tmp;
6035 struct rq *rq = arg;
6036 struct rq_flags rf;
6037
6038 rq_lock(rq, &rf);
6039
6040 /*
6041 * Iterating over the list can trigger several call to
6042 * update_rq_clock() in unthrottle_cfs_rq().
6043 * Do it once and skip the potential next ones.
6044 */
6045 update_rq_clock(rq);
6046 rq_clock_start_loop_update(rq);
6047
6048 /*
6049 * Since we hold rq lock we're safe from concurrent manipulation of
6050 * the CSD list. However, this RCU critical section annotates the
6051 * fact that we pair with sched_free_group_rcu(), so that we cannot
6052 * race with group being freed in the window between removing it
6053 * from the list and advancing to the next entry in the list.
6054 */
6055 rcu_read_lock();
6056
6057 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
6058 throttled_csd_list) {
6059 list_del_init(&cursor->throttled_csd_list);
6060
6061 if (cfs_rq_throttled(cursor))
6062 unthrottle_cfs_rq(cursor);
6063 }
6064
6065 rcu_read_unlock();
6066
6067 rq_clock_stop_loop_update(rq);
6068 rq_unlock(rq, &rf);
6069 }
6070
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6071 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6072 {
6073 struct rq *rq = rq_of(cfs_rq);
6074 bool first;
6075
6076 if (rq == this_rq()) {
6077 unthrottle_cfs_rq(cfs_rq);
6078 return;
6079 }
6080
6081 /* Already enqueued */
6082 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list)))
6083 return;
6084
6085 first = list_empty(&rq->cfsb_csd_list);
6086 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
6087 if (first)
6088 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
6089 }
6090
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)6091 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
6092 {
6093 lockdep_assert_rq_held(rq_of(cfs_rq));
6094
6095 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) ||
6096 cfs_rq->runtime_remaining <= 0))
6097 return;
6098
6099 __unthrottle_cfs_rq_async(cfs_rq);
6100 }
6101
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)6102 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
6103 {
6104 int this_cpu = smp_processor_id();
6105 u64 runtime, remaining = 1;
6106 bool throttled = false;
6107 struct cfs_rq *cfs_rq, *tmp;
6108 struct rq_flags rf;
6109 struct rq *rq;
6110 LIST_HEAD(local_unthrottle);
6111
6112 rcu_read_lock();
6113 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
6114 throttled_list) {
6115 rq = rq_of(cfs_rq);
6116
6117 if (!remaining) {
6118 throttled = true;
6119 break;
6120 }
6121
6122 rq_lock_irqsave(rq, &rf);
6123 if (!cfs_rq_throttled(cfs_rq))
6124 goto next;
6125
6126 /* Already queued for async unthrottle */
6127 if (!list_empty(&cfs_rq->throttled_csd_list))
6128 goto next;
6129
6130 /* By the above checks, this should never be true */
6131 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0);
6132
6133 raw_spin_lock(&cfs_b->lock);
6134 runtime = -cfs_rq->runtime_remaining + 1;
6135 if (runtime > cfs_b->runtime)
6136 runtime = cfs_b->runtime;
6137 cfs_b->runtime -= runtime;
6138 remaining = cfs_b->runtime;
6139 raw_spin_unlock(&cfs_b->lock);
6140
6141 cfs_rq->runtime_remaining += runtime;
6142
6143 /* we check whether we're throttled above */
6144 if (cfs_rq->runtime_remaining > 0) {
6145 if (cpu_of(rq) != this_cpu) {
6146 unthrottle_cfs_rq_async(cfs_rq);
6147 } else {
6148 /*
6149 * We currently only expect to be unthrottling
6150 * a single cfs_rq locally.
6151 */
6152 WARN_ON_ONCE(!list_empty(&local_unthrottle));
6153 list_add_tail(&cfs_rq->throttled_csd_list,
6154 &local_unthrottle);
6155 }
6156 } else {
6157 throttled = true;
6158 }
6159
6160 next:
6161 rq_unlock_irqrestore(rq, &rf);
6162 }
6163
6164 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle,
6165 throttled_csd_list) {
6166 struct rq *rq = rq_of(cfs_rq);
6167
6168 rq_lock_irqsave(rq, &rf);
6169
6170 list_del_init(&cfs_rq->throttled_csd_list);
6171
6172 if (cfs_rq_throttled(cfs_rq))
6173 unthrottle_cfs_rq(cfs_rq);
6174
6175 rq_unlock_irqrestore(rq, &rf);
6176 }
6177 WARN_ON_ONCE(!list_empty(&local_unthrottle));
6178
6179 rcu_read_unlock();
6180
6181 return throttled;
6182 }
6183
6184 /*
6185 * Responsible for refilling a task_group's bandwidth and unthrottling its
6186 * cfs_rqs as appropriate. If there has been no activity within the last
6187 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6188 * used to track this state.
6189 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6190 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6191 {
6192 int throttled;
6193
6194 /* no need to continue the timer with no bandwidth constraint */
6195 if (cfs_b->quota == RUNTIME_INF)
6196 goto out_deactivate;
6197
6198 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6199 cfs_b->nr_periods += overrun;
6200
6201 /* Refill extra burst quota even if cfs_b->idle */
6202 __refill_cfs_bandwidth_runtime(cfs_b);
6203
6204 /*
6205 * idle depends on !throttled (for the case of a large deficit), and if
6206 * we're going inactive then everything else can be deferred
6207 */
6208 if (cfs_b->idle && !throttled)
6209 goto out_deactivate;
6210
6211 if (!throttled) {
6212 /* mark as potentially idle for the upcoming period */
6213 cfs_b->idle = 1;
6214 return 0;
6215 }
6216
6217 /* account preceding periods in which throttling occurred */
6218 cfs_b->nr_throttled += overrun;
6219
6220 /*
6221 * This check is repeated as we release cfs_b->lock while we unthrottle.
6222 */
6223 while (throttled && cfs_b->runtime > 0) {
6224 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6225 /* we can't nest cfs_b->lock while distributing bandwidth */
6226 throttled = distribute_cfs_runtime(cfs_b);
6227 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6228 }
6229
6230 /*
6231 * While we are ensured activity in the period following an
6232 * unthrottle, this also covers the case in which the new bandwidth is
6233 * insufficient to cover the existing bandwidth deficit. (Forcing the
6234 * timer to remain active while there are any throttled entities.)
6235 */
6236 cfs_b->idle = 0;
6237
6238 return 0;
6239
6240 out_deactivate:
6241 return 1;
6242 }
6243
6244 /* a cfs_rq won't donate quota below this amount */
6245 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6246 /* minimum remaining period time to redistribute slack quota */
6247 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6248 /* how long we wait to gather additional slack before distributing */
6249 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6250
6251 /*
6252 * Are we near the end of the current quota period?
6253 *
6254 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6255 * hrtimer base being cleared by hrtimer_start. In the case of
6256 * migrate_hrtimers, base is never cleared, so we are fine.
6257 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6258 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6259 {
6260 struct hrtimer *refresh_timer = &cfs_b->period_timer;
6261 s64 remaining;
6262
6263 /* if the call-back is running a quota refresh is already occurring */
6264 if (hrtimer_callback_running(refresh_timer))
6265 return 1;
6266
6267 /* is a quota refresh about to occur? */
6268 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6269 if (remaining < (s64)min_expire)
6270 return 1;
6271
6272 return 0;
6273 }
6274
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6275 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6276 {
6277 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6278
6279 /* if there's a quota refresh soon don't bother with slack */
6280 if (runtime_refresh_within(cfs_b, min_left))
6281 return;
6282
6283 /* don't push forwards an existing deferred unthrottle */
6284 if (cfs_b->slack_started)
6285 return;
6286 cfs_b->slack_started = true;
6287
6288 hrtimer_start(&cfs_b->slack_timer,
6289 ns_to_ktime(cfs_bandwidth_slack_period),
6290 HRTIMER_MODE_REL);
6291 }
6292
6293 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6294 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6295 {
6296 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6297 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6298
6299 if (slack_runtime <= 0)
6300 return;
6301
6302 raw_spin_lock(&cfs_b->lock);
6303 if (cfs_b->quota != RUNTIME_INF) {
6304 cfs_b->runtime += slack_runtime;
6305
6306 /* we are under rq->lock, defer unthrottling using a timer */
6307 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6308 !list_empty(&cfs_b->throttled_cfs_rq))
6309 start_cfs_slack_bandwidth(cfs_b);
6310 }
6311 raw_spin_unlock(&cfs_b->lock);
6312
6313 /* even if it's not valid for return we don't want to try again */
6314 cfs_rq->runtime_remaining -= slack_runtime;
6315 }
6316
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6317 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6318 {
6319 if (!cfs_bandwidth_used())
6320 return;
6321
6322 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued)
6323 return;
6324
6325 __return_cfs_rq_runtime(cfs_rq);
6326 }
6327
6328 /*
6329 * This is done with a timer (instead of inline with bandwidth return) since
6330 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6331 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6332 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6333 {
6334 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6335 unsigned long flags;
6336
6337 /* confirm we're still not at a refresh boundary */
6338 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6339 cfs_b->slack_started = false;
6340
6341 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6342 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6343 return;
6344 }
6345
6346 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6347 runtime = cfs_b->runtime;
6348
6349 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6350
6351 if (!runtime)
6352 return;
6353
6354 distribute_cfs_runtime(cfs_b);
6355 }
6356
6357 /*
6358 * When a group wakes up we want to make sure that its quota is not already
6359 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6360 * runtime as update_curr() throttling can not trigger until it's on-rq.
6361 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6362 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6363 {
6364 if (!cfs_bandwidth_used())
6365 return;
6366
6367 /* an active group must be handled by the update_curr()->put() path */
6368 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6369 return;
6370
6371 /* ensure the group is not already throttled */
6372 if (cfs_rq_throttled(cfs_rq))
6373 return;
6374
6375 /* update runtime allocation */
6376 account_cfs_rq_runtime(cfs_rq, 0);
6377 if (cfs_rq->runtime_remaining <= 0)
6378 throttle_cfs_rq(cfs_rq);
6379 }
6380
sync_throttle(struct task_group * tg,int cpu)6381 static void sync_throttle(struct task_group *tg, int cpu)
6382 {
6383 struct cfs_rq *pcfs_rq, *cfs_rq;
6384
6385 if (!cfs_bandwidth_used())
6386 return;
6387
6388 if (!tg->parent)
6389 return;
6390
6391 cfs_rq = tg->cfs_rq[cpu];
6392 pcfs_rq = tg->parent->cfs_rq[cpu];
6393
6394 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6395 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6396
6397 /*
6398 * It is not enough to sync the "pelt_clock_throttled" indicator
6399 * with the parent cfs_rq when the hierarchy is not queued.
6400 * Always join a throttled hierarchy with PELT clock throttled
6401 * and leaf it to the first enqueue, or distribution to
6402 * unthrottle the PELT clock.
6403 */
6404 if (cfs_rq->throttle_count)
6405 cfs_rq->pelt_clock_throttled = 1;
6406 }
6407
6408 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6409 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6410 {
6411 if (!cfs_bandwidth_used())
6412 return false;
6413
6414 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6415 return false;
6416
6417 /*
6418 * it's possible for a throttled entity to be forced into a running
6419 * state (e.g. set_curr_task), in this case we're finished.
6420 */
6421 if (cfs_rq_throttled(cfs_rq))
6422 return true;
6423
6424 return throttle_cfs_rq(cfs_rq);
6425 }
6426
sched_cfs_slack_timer(struct hrtimer * timer)6427 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6428 {
6429 struct cfs_bandwidth *cfs_b =
6430 container_of(timer, struct cfs_bandwidth, slack_timer);
6431
6432 do_sched_cfs_slack_timer(cfs_b);
6433
6434 return HRTIMER_NORESTART;
6435 }
6436
sched_cfs_period_timer(struct hrtimer * timer)6437 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6438 {
6439 struct cfs_bandwidth *cfs_b =
6440 container_of(timer, struct cfs_bandwidth, period_timer);
6441 unsigned long flags;
6442 int overrun;
6443 int idle = 0;
6444 int count = 0;
6445
6446 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6447 for (;;) {
6448 overrun = hrtimer_forward_now(timer, cfs_b->period);
6449 if (!overrun)
6450 break;
6451
6452 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6453
6454 if (++count > 3) {
6455 u64 new, old = ktime_to_ns(cfs_b->period);
6456
6457 /*
6458 * Grow period by a factor of 2 to avoid losing precision.
6459 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6460 * to fail.
6461 */
6462 new = old * 2;
6463 if (new < max_bw_quota_period_us * NSEC_PER_USEC) {
6464 cfs_b->period = ns_to_ktime(new);
6465 cfs_b->quota *= 2;
6466 cfs_b->burst *= 2;
6467
6468 pr_warn_ratelimited(
6469 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6470 smp_processor_id(),
6471 div_u64(new, NSEC_PER_USEC),
6472 div_u64(cfs_b->quota, NSEC_PER_USEC));
6473 } else {
6474 pr_warn_ratelimited(
6475 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6476 smp_processor_id(),
6477 div_u64(old, NSEC_PER_USEC),
6478 div_u64(cfs_b->quota, NSEC_PER_USEC));
6479 }
6480
6481 /* reset count so we don't come right back in here */
6482 count = 0;
6483 }
6484 }
6485 if (idle)
6486 cfs_b->period_active = 0;
6487 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6488
6489 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6490 }
6491
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6492 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6493 {
6494 raw_spin_lock_init(&cfs_b->lock);
6495 cfs_b->runtime = 0;
6496 cfs_b->quota = RUNTIME_INF;
6497 cfs_b->period = us_to_ktime(default_bw_period_us());
6498 cfs_b->burst = 0;
6499 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6500
6501 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6502 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC,
6503 HRTIMER_MODE_ABS_PINNED);
6504
6505 /* Add a random offset so that timers interleave */
6506 hrtimer_set_expires(&cfs_b->period_timer,
6507 get_random_u32_below(cfs_b->period));
6508 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC,
6509 HRTIMER_MODE_REL);
6510 cfs_b->slack_started = false;
6511 }
6512
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6513 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6514 {
6515 cfs_rq->runtime_enabled = 0;
6516 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6517 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6518 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list);
6519 }
6520
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6521 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6522 {
6523 lockdep_assert_held(&cfs_b->lock);
6524
6525 if (cfs_b->period_active)
6526 return;
6527
6528 cfs_b->period_active = 1;
6529 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6530 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6531 }
6532
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6533 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6534 {
6535 int __maybe_unused i;
6536
6537 /* init_cfs_bandwidth() was not called */
6538 if (!cfs_b->throttled_cfs_rq.next)
6539 return;
6540
6541 hrtimer_cancel(&cfs_b->period_timer);
6542 hrtimer_cancel(&cfs_b->slack_timer);
6543
6544 /*
6545 * It is possible that we still have some cfs_rq's pending on a CSD
6546 * list, though this race is very rare. In order for this to occur, we
6547 * must have raced with the last task leaving the group while there
6548 * exist throttled cfs_rq(s), and the period_timer must have queued the
6549 * CSD item but the remote cpu has not yet processed it. To handle this,
6550 * we can simply flush all pending CSD work inline here. We're
6551 * guaranteed at this point that no additional cfs_rq of this group can
6552 * join a CSD list.
6553 */
6554 for_each_possible_cpu(i) {
6555 struct rq *rq = cpu_rq(i);
6556 unsigned long flags;
6557
6558 if (list_empty(&rq->cfsb_csd_list))
6559 continue;
6560
6561 local_irq_save(flags);
6562 __cfsb_csd_unthrottle(rq);
6563 local_irq_restore(flags);
6564 }
6565 }
6566
6567 /*
6568 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6569 *
6570 * The race is harmless, since modifying bandwidth settings of unhooked group
6571 * bits doesn't do much.
6572 */
6573
6574 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6575 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6576 {
6577 struct task_group *tg;
6578
6579 lockdep_assert_rq_held(rq);
6580
6581 rcu_read_lock();
6582 list_for_each_entry_rcu(tg, &task_groups, list) {
6583 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6584 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6585
6586 raw_spin_lock(&cfs_b->lock);
6587 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6588 raw_spin_unlock(&cfs_b->lock);
6589 }
6590 rcu_read_unlock();
6591 }
6592
6593 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6594 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6595 {
6596 struct task_group *tg;
6597
6598 lockdep_assert_rq_held(rq);
6599
6600 // Do not unthrottle for an active CPU
6601 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask))
6602 return;
6603
6604 /*
6605 * The rq clock has already been updated in the
6606 * set_rq_offline(), so we should skip updating
6607 * the rq clock again in unthrottle_cfs_rq().
6608 */
6609 rq_clock_start_loop_update(rq);
6610
6611 rcu_read_lock();
6612 list_for_each_entry_rcu(tg, &task_groups, list) {
6613 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6614
6615 if (!cfs_rq->runtime_enabled)
6616 continue;
6617
6618 /*
6619 * Offline rq is schedulable till CPU is completely disabled
6620 * in take_cpu_down(), so we prevent new cfs throttling here.
6621 */
6622 cfs_rq->runtime_enabled = 0;
6623
6624 if (!cfs_rq_throttled(cfs_rq))
6625 continue;
6626
6627 /*
6628 * clock_task is not advancing so we just need to make sure
6629 * there's some valid quota amount
6630 */
6631 cfs_rq->runtime_remaining = 1;
6632 unthrottle_cfs_rq(cfs_rq);
6633 }
6634 rcu_read_unlock();
6635
6636 rq_clock_stop_loop_update(rq);
6637 }
6638
cfs_task_bw_constrained(struct task_struct * p)6639 bool cfs_task_bw_constrained(struct task_struct *p)
6640 {
6641 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6642
6643 if (!cfs_bandwidth_used())
6644 return false;
6645
6646 if (cfs_rq->runtime_enabled ||
6647 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6648 return true;
6649
6650 return false;
6651 }
6652
6653 #ifdef CONFIG_NO_HZ_FULL
6654 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6655 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6656 {
6657 int cpu = cpu_of(rq);
6658
6659 if (!cfs_bandwidth_used())
6660 return;
6661
6662 if (!tick_nohz_full_cpu(cpu))
6663 return;
6664
6665 if (rq->nr_running != 1)
6666 return;
6667
6668 /*
6669 * We know there is only one task runnable and we've just picked it. The
6670 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6671 * be otherwise able to stop the tick. Just need to check if we are using
6672 * bandwidth control.
6673 */
6674 if (cfs_task_bw_constrained(p))
6675 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6676 }
6677 #endif /* CONFIG_NO_HZ_FULL */
6678
6679 #else /* !CONFIG_CFS_BANDWIDTH: */
6680
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6681 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6682 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6683 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6684 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6685 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
task_throttle_setup_work(struct task_struct * p)6686 static void task_throttle_setup_work(struct task_struct *p) {}
task_is_throttled(struct task_struct * p)6687 static bool task_is_throttled(struct task_struct *p) { return false; }
dequeue_throttled_task(struct task_struct * p,int flags)6688 static void dequeue_throttled_task(struct task_struct *p, int flags) {}
enqueue_throttled_task(struct task_struct * p)6689 static bool enqueue_throttled_task(struct task_struct *p) { return false; }
record_throttle_clock(struct cfs_rq * cfs_rq)6690 static void record_throttle_clock(struct cfs_rq *cfs_rq) {}
6691
cfs_rq_throttled(struct cfs_rq * cfs_rq)6692 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6693 {
6694 return 0;
6695 }
6696
cfs_rq_pelt_clock_throttled(struct cfs_rq * cfs_rq)6697 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq)
6698 {
6699 return false;
6700 }
6701
throttled_hierarchy(struct cfs_rq * cfs_rq)6702 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6703 {
6704 return 0;
6705 }
6706
lb_throttled_hierarchy(struct task_struct * p,int dst_cpu)6707 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu)
6708 {
6709 return 0;
6710 }
6711
6712 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6713 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6714 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6715 #endif
6716
tg_cfs_bandwidth(struct task_group * tg)6717 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6718 {
6719 return NULL;
6720 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6721 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6722 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6723 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6724 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6725 bool cfs_task_bw_constrained(struct task_struct *p)
6726 {
6727 return false;
6728 }
6729 #endif
6730 #endif /* !CONFIG_CFS_BANDWIDTH */
6731
6732 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6733 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6734 #endif
6735
6736 /**************************************************
6737 * CFS operations on tasks:
6738 */
6739
6740 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6741 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6742 {
6743 struct sched_entity *se = &p->se;
6744
6745 WARN_ON_ONCE(task_rq(p) != rq);
6746
6747 if (rq->cfs.h_nr_queued > 1) {
6748 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6749 u64 slice = se->slice;
6750 s64 delta = slice - ran;
6751
6752 if (delta < 0) {
6753 if (task_current_donor(rq, p))
6754 resched_curr(rq);
6755 return;
6756 }
6757 hrtick_start(rq, delta);
6758 }
6759 }
6760
6761 /*
6762 * called from enqueue/dequeue and updates the hrtick when the
6763 * current task is from our class and nr_running is low enough
6764 * to matter.
6765 */
hrtick_update(struct rq * rq)6766 static void hrtick_update(struct rq *rq)
6767 {
6768 struct task_struct *donor = rq->donor;
6769
6770 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class)
6771 return;
6772
6773 hrtick_start_fair(rq, donor);
6774 }
6775 #else /* !CONFIG_SCHED_HRTICK: */
6776 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)6777 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6778 {
6779 }
6780
hrtick_update(struct rq * rq)6781 static inline void hrtick_update(struct rq *rq)
6782 {
6783 }
6784 #endif /* !CONFIG_SCHED_HRTICK */
6785
cpu_overutilized(int cpu)6786 static inline bool cpu_overutilized(int cpu)
6787 {
6788 unsigned long rq_util_min, rq_util_max;
6789
6790 if (!sched_energy_enabled())
6791 return false;
6792
6793 rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6794 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6795
6796 /* Return true only if the utilization doesn't fit CPU's capacity */
6797 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6798 }
6799
6800 /*
6801 * overutilized value make sense only if EAS is enabled
6802 */
is_rd_overutilized(struct root_domain * rd)6803 static inline bool is_rd_overutilized(struct root_domain *rd)
6804 {
6805 return !sched_energy_enabled() || READ_ONCE(rd->overutilized);
6806 }
6807
set_rd_overutilized(struct root_domain * rd,bool flag)6808 static inline void set_rd_overutilized(struct root_domain *rd, bool flag)
6809 {
6810 if (!sched_energy_enabled())
6811 return;
6812
6813 WRITE_ONCE(rd->overutilized, flag);
6814 trace_sched_overutilized_tp(rd, flag);
6815 }
6816
check_update_overutilized_status(struct rq * rq)6817 static inline void check_update_overutilized_status(struct rq *rq)
6818 {
6819 /*
6820 * overutilized field is used for load balancing decisions only
6821 * if energy aware scheduler is being used
6822 */
6823
6824 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu))
6825 set_rd_overutilized(rq->rd, 1);
6826 }
6827
6828 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)6829 static int sched_idle_rq(struct rq *rq)
6830 {
6831 return unlikely(rq->nr_running == rq->cfs.h_nr_idle &&
6832 rq->nr_running);
6833 }
6834
sched_idle_cpu(int cpu)6835 static int sched_idle_cpu(int cpu)
6836 {
6837 return sched_idle_rq(cpu_rq(cpu));
6838 }
6839
6840 static void
requeue_delayed_entity(struct sched_entity * se)6841 requeue_delayed_entity(struct sched_entity *se)
6842 {
6843 struct cfs_rq *cfs_rq = cfs_rq_of(se);
6844
6845 /*
6846 * se->sched_delayed should imply: se->on_rq == 1.
6847 * Because a delayed entity is one that is still on
6848 * the runqueue competing until elegibility.
6849 */
6850 WARN_ON_ONCE(!se->sched_delayed);
6851 WARN_ON_ONCE(!se->on_rq);
6852
6853 if (sched_feat(DELAY_ZERO)) {
6854 update_entity_lag(cfs_rq, se);
6855 if (se->vlag > 0) {
6856 cfs_rq->nr_queued--;
6857 if (se != cfs_rq->curr)
6858 __dequeue_entity(cfs_rq, se);
6859 se->vlag = 0;
6860 place_entity(cfs_rq, se, 0);
6861 if (se != cfs_rq->curr)
6862 __enqueue_entity(cfs_rq, se);
6863 cfs_rq->nr_queued++;
6864 }
6865 }
6866
6867 update_load_avg(cfs_rq, se, 0);
6868 clear_delayed(se);
6869 }
6870
6871 /*
6872 * The enqueue_task method is called before nr_running is
6873 * increased. Here we update the fair scheduling stats and
6874 * then put the task into the rbtree:
6875 */
6876 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)6877 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6878 {
6879 struct cfs_rq *cfs_rq;
6880 struct sched_entity *se = &p->se;
6881 int h_nr_idle = task_has_idle_policy(p);
6882 int h_nr_runnable = 1;
6883 int task_new = !(flags & ENQUEUE_WAKEUP);
6884 int rq_h_nr_queued = rq->cfs.h_nr_queued;
6885 u64 slice = 0;
6886
6887 if (task_is_throttled(p) && enqueue_throttled_task(p))
6888 return;
6889
6890 /*
6891 * The code below (indirectly) updates schedutil which looks at
6892 * the cfs_rq utilization to select a frequency.
6893 * Let's add the task's estimated utilization to the cfs_rq's
6894 * estimated utilization, before we update schedutil.
6895 */
6896 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED))
6897 util_est_enqueue(&rq->cfs, p);
6898
6899 if (flags & ENQUEUE_DELAYED) {
6900 requeue_delayed_entity(se);
6901 return;
6902 }
6903
6904 /*
6905 * If in_iowait is set, the code below may not trigger any cpufreq
6906 * utilization updates, so do it here explicitly with the IOWAIT flag
6907 * passed.
6908 */
6909 if (p->in_iowait)
6910 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6911
6912 if (task_new && se->sched_delayed)
6913 h_nr_runnable = 0;
6914
6915 for_each_sched_entity(se) {
6916 if (se->on_rq) {
6917 if (se->sched_delayed)
6918 requeue_delayed_entity(se);
6919 break;
6920 }
6921 cfs_rq = cfs_rq_of(se);
6922
6923 /*
6924 * Basically set the slice of group entries to the min_slice of
6925 * their respective cfs_rq. This ensures the group can service
6926 * its entities in the desired time-frame.
6927 */
6928 if (slice) {
6929 se->slice = slice;
6930 se->custom_slice = 1;
6931 }
6932 enqueue_entity(cfs_rq, se, flags);
6933 slice = cfs_rq_min_slice(cfs_rq);
6934
6935 cfs_rq->h_nr_runnable += h_nr_runnable;
6936 cfs_rq->h_nr_queued++;
6937 cfs_rq->h_nr_idle += h_nr_idle;
6938
6939 if (cfs_rq_is_idle(cfs_rq))
6940 h_nr_idle = 1;
6941
6942 flags = ENQUEUE_WAKEUP;
6943 }
6944
6945 for_each_sched_entity(se) {
6946 cfs_rq = cfs_rq_of(se);
6947
6948 update_load_avg(cfs_rq, se, UPDATE_TG);
6949 se_update_runnable(se);
6950 update_cfs_group(se);
6951
6952 se->slice = slice;
6953 if (se != cfs_rq->curr)
6954 min_vruntime_cb_propagate(&se->run_node, NULL);
6955 slice = cfs_rq_min_slice(cfs_rq);
6956
6957 cfs_rq->h_nr_runnable += h_nr_runnable;
6958 cfs_rq->h_nr_queued++;
6959 cfs_rq->h_nr_idle += h_nr_idle;
6960
6961 if (cfs_rq_is_idle(cfs_rq))
6962 h_nr_idle = 1;
6963 }
6964
6965 if (!rq_h_nr_queued && rq->cfs.h_nr_queued)
6966 dl_server_start(&rq->fair_server);
6967
6968 /* At this point se is NULL and we are at root level*/
6969 add_nr_running(rq, 1);
6970
6971 /*
6972 * Since new tasks are assigned an initial util_avg equal to
6973 * half of the spare capacity of their CPU, tiny tasks have the
6974 * ability to cross the overutilized threshold, which will
6975 * result in the load balancer ruining all the task placement
6976 * done by EAS. As a way to mitigate that effect, do not account
6977 * for the first enqueue operation of new tasks during the
6978 * overutilized flag detection.
6979 *
6980 * A better way of solving this problem would be to wait for
6981 * the PELT signals of tasks to converge before taking them
6982 * into account, but that is not straightforward to implement,
6983 * and the following generally works well enough in practice.
6984 */
6985 if (!task_new)
6986 check_update_overutilized_status(rq);
6987
6988 assert_list_leaf_cfs_rq(rq);
6989
6990 hrtick_update(rq);
6991 }
6992
6993 /*
6994 * Basically dequeue_task_fair(), except it can deal with dequeue_entity()
6995 * failing half-way through and resume the dequeue later.
6996 *
6997 * Returns:
6998 * -1 - dequeue delayed
6999 * 0 - dequeue throttled
7000 * 1 - dequeue complete
7001 */
dequeue_entities(struct rq * rq,struct sched_entity * se,int flags)7002 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags)
7003 {
7004 bool was_sched_idle = sched_idle_rq(rq);
7005 bool task_sleep = flags & DEQUEUE_SLEEP;
7006 bool task_delayed = flags & DEQUEUE_DELAYED;
7007 bool task_throttled = flags & DEQUEUE_THROTTLE;
7008 struct task_struct *p = NULL;
7009 int h_nr_idle = 0;
7010 int h_nr_queued = 0;
7011 int h_nr_runnable = 0;
7012 struct cfs_rq *cfs_rq;
7013 u64 slice = 0;
7014
7015 if (entity_is_task(se)) {
7016 p = task_of(se);
7017 h_nr_queued = 1;
7018 h_nr_idle = task_has_idle_policy(p);
7019 if (task_sleep || task_delayed || !se->sched_delayed)
7020 h_nr_runnable = 1;
7021 }
7022
7023 for_each_sched_entity(se) {
7024 cfs_rq = cfs_rq_of(se);
7025
7026 if (!dequeue_entity(cfs_rq, se, flags)) {
7027 if (p && &p->se == se)
7028 return -1;
7029
7030 slice = cfs_rq_min_slice(cfs_rq);
7031 break;
7032 }
7033
7034 cfs_rq->h_nr_runnable -= h_nr_runnable;
7035 cfs_rq->h_nr_queued -= h_nr_queued;
7036 cfs_rq->h_nr_idle -= h_nr_idle;
7037
7038 if (cfs_rq_is_idle(cfs_rq))
7039 h_nr_idle = h_nr_queued;
7040
7041 if (throttled_hierarchy(cfs_rq) && task_throttled)
7042 record_throttle_clock(cfs_rq);
7043
7044 /* Don't dequeue parent if it has other entities besides us */
7045 if (cfs_rq->load.weight) {
7046 slice = cfs_rq_min_slice(cfs_rq);
7047
7048 /* Avoid re-evaluating load for this entity: */
7049 se = parent_entity(se);
7050 /*
7051 * Bias pick_next to pick a task from this cfs_rq, as
7052 * p is sleeping when it is within its sched_slice.
7053 */
7054 if (task_sleep && se)
7055 set_next_buddy(se);
7056 break;
7057 }
7058 flags |= DEQUEUE_SLEEP;
7059 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL);
7060 }
7061
7062 for_each_sched_entity(se) {
7063 cfs_rq = cfs_rq_of(se);
7064
7065 update_load_avg(cfs_rq, se, UPDATE_TG);
7066 se_update_runnable(se);
7067 update_cfs_group(se);
7068
7069 se->slice = slice;
7070 if (se != cfs_rq->curr)
7071 min_vruntime_cb_propagate(&se->run_node, NULL);
7072 slice = cfs_rq_min_slice(cfs_rq);
7073
7074 cfs_rq->h_nr_runnable -= h_nr_runnable;
7075 cfs_rq->h_nr_queued -= h_nr_queued;
7076 cfs_rq->h_nr_idle -= h_nr_idle;
7077
7078 if (cfs_rq_is_idle(cfs_rq))
7079 h_nr_idle = h_nr_queued;
7080
7081 if (throttled_hierarchy(cfs_rq) && task_throttled)
7082 record_throttle_clock(cfs_rq);
7083 }
7084
7085 sub_nr_running(rq, h_nr_queued);
7086
7087 /* balance early to pull high priority tasks */
7088 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
7089 rq->next_balance = jiffies;
7090
7091 if (p && task_delayed) {
7092 WARN_ON_ONCE(!task_sleep);
7093 WARN_ON_ONCE(p->on_rq != 1);
7094
7095 /* Fix-up what dequeue_task_fair() skipped */
7096 hrtick_update(rq);
7097
7098 /*
7099 * Fix-up what block_task() skipped.
7100 *
7101 * Must be last, @p might not be valid after this.
7102 */
7103 __block_task(rq, p);
7104 }
7105
7106 return 1;
7107 }
7108
7109 /*
7110 * The dequeue_task method is called before nr_running is
7111 * decreased. We remove the task from the rbtree and
7112 * update the fair scheduling stats:
7113 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)7114 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
7115 {
7116 if (task_is_throttled(p)) {
7117 dequeue_throttled_task(p, flags);
7118 return true;
7119 }
7120
7121 if (!p->se.sched_delayed)
7122 util_est_dequeue(&rq->cfs, p);
7123
7124 util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP);
7125 if (dequeue_entities(rq, &p->se, flags) < 0)
7126 return false;
7127
7128 /*
7129 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED).
7130 */
7131
7132 hrtick_update(rq);
7133 return true;
7134 }
7135
cfs_h_nr_delayed(struct rq * rq)7136 static inline unsigned int cfs_h_nr_delayed(struct rq *rq)
7137 {
7138 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable);
7139 }
7140
7141 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */
7142 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
7143 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
7144 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
7145
7146 #ifdef CONFIG_NO_HZ_COMMON
7147
7148 static struct {
7149 cpumask_var_t idle_cpus_mask;
7150 atomic_t nr_cpus;
7151 int has_blocked; /* Idle CPUS has blocked load */
7152 int needs_update; /* Newly idle CPUs need their next_balance collated */
7153 unsigned long next_balance; /* in jiffy units */
7154 unsigned long next_blocked; /* Next update of blocked load in jiffies */
7155 } nohz ____cacheline_aligned;
7156
7157 #endif /* CONFIG_NO_HZ_COMMON */
7158
cpu_load(struct rq * rq)7159 static unsigned long cpu_load(struct rq *rq)
7160 {
7161 return cfs_rq_load_avg(&rq->cfs);
7162 }
7163
7164 /*
7165 * cpu_load_without - compute CPU load without any contributions from *p
7166 * @cpu: the CPU which load is requested
7167 * @p: the task which load should be discounted
7168 *
7169 * The load of a CPU is defined by the load of tasks currently enqueued on that
7170 * CPU as well as tasks which are currently sleeping after an execution on that
7171 * CPU.
7172 *
7173 * This method returns the load of the specified CPU by discounting the load of
7174 * the specified task, whenever the task is currently contributing to the CPU
7175 * load.
7176 */
cpu_load_without(struct rq * rq,struct task_struct * p)7177 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
7178 {
7179 struct cfs_rq *cfs_rq;
7180 unsigned int load;
7181
7182 /* Task has no contribution or is new */
7183 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7184 return cpu_load(rq);
7185
7186 cfs_rq = &rq->cfs;
7187 load = READ_ONCE(cfs_rq->avg.load_avg);
7188
7189 /* Discount task's util from CPU's util */
7190 lsub_positive(&load, task_h_load(p));
7191
7192 return load;
7193 }
7194
cpu_runnable(struct rq * rq)7195 static unsigned long cpu_runnable(struct rq *rq)
7196 {
7197 return cfs_rq_runnable_avg(&rq->cfs);
7198 }
7199
cpu_runnable_without(struct rq * rq,struct task_struct * p)7200 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
7201 {
7202 struct cfs_rq *cfs_rq;
7203 unsigned int runnable;
7204
7205 /* Task has no contribution or is new */
7206 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7207 return cpu_runnable(rq);
7208
7209 cfs_rq = &rq->cfs;
7210 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7211
7212 /* Discount task's runnable from CPU's runnable */
7213 lsub_positive(&runnable, p->se.avg.runnable_avg);
7214
7215 return runnable;
7216 }
7217
capacity_of(int cpu)7218 static unsigned long capacity_of(int cpu)
7219 {
7220 return cpu_rq(cpu)->cpu_capacity;
7221 }
7222
record_wakee(struct task_struct * p)7223 static void record_wakee(struct task_struct *p)
7224 {
7225 /*
7226 * Only decay a single time; tasks that have less then 1 wakeup per
7227 * jiffy will not have built up many flips.
7228 */
7229 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
7230 current->wakee_flips >>= 1;
7231 current->wakee_flip_decay_ts = jiffies;
7232 }
7233
7234 if (current->last_wakee != p) {
7235 current->last_wakee = p;
7236 current->wakee_flips++;
7237 }
7238 }
7239
7240 /*
7241 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
7242 *
7243 * A waker of many should wake a different task than the one last awakened
7244 * at a frequency roughly N times higher than one of its wakees.
7245 *
7246 * In order to determine whether we should let the load spread vs consolidating
7247 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
7248 * partner, and a factor of lls_size higher frequency in the other.
7249 *
7250 * With both conditions met, we can be relatively sure that the relationship is
7251 * non-monogamous, with partner count exceeding socket size.
7252 *
7253 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
7254 * whatever is irrelevant, spread criteria is apparent partner count exceeds
7255 * socket size.
7256 */
wake_wide(struct task_struct * p)7257 static int wake_wide(struct task_struct *p)
7258 {
7259 unsigned int master = current->wakee_flips;
7260 unsigned int slave = p->wakee_flips;
7261 int factor = __this_cpu_read(sd_llc_size);
7262
7263 if (master < slave)
7264 swap(master, slave);
7265 if (slave < factor || master < slave * factor)
7266 return 0;
7267 return 1;
7268 }
7269
7270 /*
7271 * The purpose of wake_affine() is to quickly determine on which CPU we can run
7272 * soonest. For the purpose of speed we only consider the waking and previous
7273 * CPU.
7274 *
7275 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
7276 * cache-affine and is (or will be) idle.
7277 *
7278 * wake_affine_weight() - considers the weight to reflect the average
7279 * scheduling latency of the CPUs. This seems to work
7280 * for the overloaded case.
7281 */
7282 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)7283 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
7284 {
7285 /*
7286 * If this_cpu is idle, it implies the wakeup is from interrupt
7287 * context. Only allow the move if cache is shared. Otherwise an
7288 * interrupt intensive workload could force all tasks onto one
7289 * node depending on the IO topology or IRQ affinity settings.
7290 *
7291 * If the prev_cpu is idle and cache affine then avoid a migration.
7292 * There is no guarantee that the cache hot data from an interrupt
7293 * is more important than cache hot data on the prev_cpu and from
7294 * a cpufreq perspective, it's better to have higher utilisation
7295 * on one CPU.
7296 */
7297 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
7298 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
7299
7300 if (sync) {
7301 struct rq *rq = cpu_rq(this_cpu);
7302
7303 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1)
7304 return this_cpu;
7305 }
7306
7307 if (available_idle_cpu(prev_cpu))
7308 return prev_cpu;
7309
7310 return nr_cpumask_bits;
7311 }
7312
7313 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7314 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7315 int this_cpu, int prev_cpu, int sync)
7316 {
7317 s64 this_eff_load, prev_eff_load;
7318 unsigned long task_load;
7319
7320 this_eff_load = cpu_load(cpu_rq(this_cpu));
7321
7322 if (sync) {
7323 unsigned long current_load = task_h_load(current);
7324
7325 if (current_load > this_eff_load)
7326 return this_cpu;
7327
7328 this_eff_load -= current_load;
7329 }
7330
7331 task_load = task_h_load(p);
7332
7333 this_eff_load += task_load;
7334 if (sched_feat(WA_BIAS))
7335 this_eff_load *= 100;
7336 this_eff_load *= capacity_of(prev_cpu);
7337
7338 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7339 prev_eff_load -= task_load;
7340 if (sched_feat(WA_BIAS))
7341 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7342 prev_eff_load *= capacity_of(this_cpu);
7343
7344 /*
7345 * If sync, adjust the weight of prev_eff_load such that if
7346 * prev_eff == this_eff that select_idle_sibling() will consider
7347 * stacking the wakee on top of the waker if no other CPU is
7348 * idle.
7349 */
7350 if (sync)
7351 prev_eff_load += 1;
7352
7353 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7354 }
7355
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7356 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7357 int this_cpu, int prev_cpu, int sync)
7358 {
7359 int target = nr_cpumask_bits;
7360
7361 if (sched_feat(WA_IDLE))
7362 target = wake_affine_idle(this_cpu, prev_cpu, sync);
7363
7364 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7365 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7366
7367 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7368 if (target != this_cpu)
7369 return prev_cpu;
7370
7371 schedstat_inc(sd->ttwu_move_affine);
7372 schedstat_inc(p->stats.nr_wakeups_affine);
7373 return target;
7374 }
7375
7376 static struct sched_group *
7377 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7378
7379 /*
7380 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group.
7381 */
7382 static int
sched_balance_find_dst_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7383 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7384 {
7385 unsigned long load, min_load = ULONG_MAX;
7386 unsigned int min_exit_latency = UINT_MAX;
7387 u64 latest_idle_timestamp = 0;
7388 int least_loaded_cpu = this_cpu;
7389 int shallowest_idle_cpu = -1;
7390 int i;
7391
7392 /* Check if we have any choice: */
7393 if (group->group_weight == 1)
7394 return cpumask_first(sched_group_span(group));
7395
7396 /* Traverse only the allowed CPUs */
7397 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7398 struct rq *rq = cpu_rq(i);
7399
7400 if (!sched_core_cookie_match(rq, p))
7401 continue;
7402
7403 if (sched_idle_cpu(i))
7404 return i;
7405
7406 if (available_idle_cpu(i)) {
7407 struct cpuidle_state *idle = idle_get_state(rq);
7408 if (idle && idle->exit_latency < min_exit_latency) {
7409 /*
7410 * We give priority to a CPU whose idle state
7411 * has the smallest exit latency irrespective
7412 * of any idle timestamp.
7413 */
7414 min_exit_latency = idle->exit_latency;
7415 latest_idle_timestamp = rq->idle_stamp;
7416 shallowest_idle_cpu = i;
7417 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
7418 rq->idle_stamp > latest_idle_timestamp) {
7419 /*
7420 * If equal or no active idle state, then
7421 * the most recently idled CPU might have
7422 * a warmer cache.
7423 */
7424 latest_idle_timestamp = rq->idle_stamp;
7425 shallowest_idle_cpu = i;
7426 }
7427 } else if (shallowest_idle_cpu == -1) {
7428 load = cpu_load(cpu_rq(i));
7429 if (load < min_load) {
7430 min_load = load;
7431 least_loaded_cpu = i;
7432 }
7433 }
7434 }
7435
7436 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7437 }
7438
sched_balance_find_dst_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7439 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p,
7440 int cpu, int prev_cpu, int sd_flag)
7441 {
7442 int new_cpu = cpu;
7443
7444 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7445 return prev_cpu;
7446
7447 /*
7448 * We need task's util for cpu_util_without, sync it up to
7449 * prev_cpu's last_update_time.
7450 */
7451 if (!(sd_flag & SD_BALANCE_FORK))
7452 sync_entity_load_avg(&p->se);
7453
7454 while (sd) {
7455 struct sched_group *group;
7456 struct sched_domain *tmp;
7457 int weight;
7458
7459 if (!(sd->flags & sd_flag)) {
7460 sd = sd->child;
7461 continue;
7462 }
7463
7464 group = sched_balance_find_dst_group(sd, p, cpu);
7465 if (!group) {
7466 sd = sd->child;
7467 continue;
7468 }
7469
7470 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu);
7471 if (new_cpu == cpu) {
7472 /* Now try balancing at a lower domain level of 'cpu': */
7473 sd = sd->child;
7474 continue;
7475 }
7476
7477 /* Now try balancing at a lower domain level of 'new_cpu': */
7478 cpu = new_cpu;
7479 weight = sd->span_weight;
7480 sd = NULL;
7481 for_each_domain(cpu, tmp) {
7482 if (weight <= tmp->span_weight)
7483 break;
7484 if (tmp->flags & sd_flag)
7485 sd = tmp;
7486 }
7487 }
7488
7489 return new_cpu;
7490 }
7491
__select_idle_cpu(int cpu,struct task_struct * p)7492 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7493 {
7494 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7495 sched_cpu_cookie_match(cpu_rq(cpu), p))
7496 return cpu;
7497
7498 return -1;
7499 }
7500
7501 #ifdef CONFIG_SCHED_SMT
7502 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7503 EXPORT_SYMBOL_GPL(sched_smt_present);
7504
set_idle_cores(int cpu,int val)7505 static inline void set_idle_cores(int cpu, int val)
7506 {
7507 struct sched_domain_shared *sds;
7508
7509 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7510 if (sds)
7511 WRITE_ONCE(sds->has_idle_cores, val);
7512 }
7513
test_idle_cores(int cpu)7514 static inline bool test_idle_cores(int cpu)
7515 {
7516 struct sched_domain_shared *sds;
7517
7518 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7519 if (sds)
7520 return READ_ONCE(sds->has_idle_cores);
7521
7522 return false;
7523 }
7524
7525 /*
7526 * Scans the local SMT mask to see if the entire core is idle, and records this
7527 * information in sd_llc_shared->has_idle_cores.
7528 *
7529 * Since SMT siblings share all cache levels, inspecting this limited remote
7530 * state should be fairly cheap.
7531 */
__update_idle_core(struct rq * rq)7532 void __update_idle_core(struct rq *rq)
7533 {
7534 int core = cpu_of(rq);
7535 int cpu;
7536
7537 rcu_read_lock();
7538 if (test_idle_cores(core))
7539 goto unlock;
7540
7541 for_each_cpu(cpu, cpu_smt_mask(core)) {
7542 if (cpu == core)
7543 continue;
7544
7545 if (!available_idle_cpu(cpu))
7546 goto unlock;
7547 }
7548
7549 set_idle_cores(core, 1);
7550 unlock:
7551 rcu_read_unlock();
7552 }
7553
7554 /*
7555 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7556 * there are no idle cores left in the system; tracked through
7557 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7558 */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7559 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7560 {
7561 bool idle = true;
7562 int cpu;
7563
7564 for_each_cpu(cpu, cpu_smt_mask(core)) {
7565 if (!available_idle_cpu(cpu)) {
7566 idle = false;
7567 if (*idle_cpu == -1) {
7568 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7569 *idle_cpu = cpu;
7570 break;
7571 }
7572 continue;
7573 }
7574 break;
7575 }
7576 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7577 *idle_cpu = cpu;
7578 }
7579
7580 if (idle)
7581 return core;
7582
7583 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7584 return -1;
7585 }
7586
7587 /*
7588 * Scan the local SMT mask for idle CPUs.
7589 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7590 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7591 {
7592 int cpu;
7593
7594 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7595 if (cpu == target)
7596 continue;
7597 /*
7598 * Check if the CPU is in the LLC scheduling domain of @target.
7599 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7600 */
7601 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7602 continue;
7603 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7604 return cpu;
7605 }
7606
7607 return -1;
7608 }
7609
7610 #else /* !CONFIG_SCHED_SMT: */
7611
set_idle_cores(int cpu,int val)7612 static inline void set_idle_cores(int cpu, int val)
7613 {
7614 }
7615
test_idle_cores(int cpu)7616 static inline bool test_idle_cores(int cpu)
7617 {
7618 return false;
7619 }
7620
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7621 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7622 {
7623 return __select_idle_cpu(core, p);
7624 }
7625
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7626 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7627 {
7628 return -1;
7629 }
7630
7631 #endif /* !CONFIG_SCHED_SMT */
7632
7633 /*
7634 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7635 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7636 * average idle time for this rq (as found in rq->avg_idle).
7637 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7638 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7639 {
7640 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7641 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7642 struct sched_domain_shared *sd_share;
7643
7644 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7645
7646 if (sched_feat(SIS_UTIL)) {
7647 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7648 if (sd_share) {
7649 /* because !--nr is the condition to stop scan */
7650 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7651 /* overloaded LLC is unlikely to have idle cpu/core */
7652 if (nr == 1)
7653 return -1;
7654 }
7655 }
7656
7657 if (static_branch_unlikely(&sched_cluster_active)) {
7658 struct sched_group *sg = sd->groups;
7659
7660 if (sg->flags & SD_CLUSTER) {
7661 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) {
7662 if (!cpumask_test_cpu(cpu, cpus))
7663 continue;
7664
7665 if (has_idle_core) {
7666 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7667 if ((unsigned int)i < nr_cpumask_bits)
7668 return i;
7669 } else {
7670 if (--nr <= 0)
7671 return -1;
7672 idle_cpu = __select_idle_cpu(cpu, p);
7673 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7674 return idle_cpu;
7675 }
7676 }
7677 cpumask_andnot(cpus, cpus, sched_group_span(sg));
7678 }
7679 }
7680
7681 for_each_cpu_wrap(cpu, cpus, target + 1) {
7682 if (has_idle_core) {
7683 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7684 if ((unsigned int)i < nr_cpumask_bits)
7685 return i;
7686
7687 } else {
7688 if (--nr <= 0)
7689 return -1;
7690 idle_cpu = __select_idle_cpu(cpu, p);
7691 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7692 break;
7693 }
7694 }
7695
7696 if (has_idle_core)
7697 set_idle_cores(target, false);
7698
7699 return idle_cpu;
7700 }
7701
7702 /*
7703 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7704 * the task fits. If no CPU is big enough, but there are idle ones, try to
7705 * maximize capacity.
7706 */
7707 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7708 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7709 {
7710 unsigned long task_util, util_min, util_max, best_cap = 0;
7711 int fits, best_fits = 0;
7712 int cpu, best_cpu = -1;
7713 struct cpumask *cpus;
7714
7715 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7716 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7717
7718 task_util = task_util_est(p);
7719 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7720 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7721
7722 for_each_cpu_wrap(cpu, cpus, target) {
7723 unsigned long cpu_cap = capacity_of(cpu);
7724
7725 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7726 continue;
7727
7728 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7729
7730 /* This CPU fits with all requirements */
7731 if (fits > 0)
7732 return cpu;
7733 /*
7734 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7735 * Look for the CPU with best capacity.
7736 */
7737 else if (fits < 0)
7738 cpu_cap = get_actual_cpu_capacity(cpu);
7739
7740 /*
7741 * First, select CPU which fits better (-1 being better than 0).
7742 * Then, select the one with best capacity at same level.
7743 */
7744 if ((fits < best_fits) ||
7745 ((fits == best_fits) && (cpu_cap > best_cap))) {
7746 best_cap = cpu_cap;
7747 best_cpu = cpu;
7748 best_fits = fits;
7749 }
7750 }
7751
7752 return best_cpu;
7753 }
7754
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)7755 static inline bool asym_fits_cpu(unsigned long util,
7756 unsigned long util_min,
7757 unsigned long util_max,
7758 int cpu)
7759 {
7760 if (sched_asym_cpucap_active())
7761 /*
7762 * Return true only if the cpu fully fits the task requirements
7763 * which include the utilization and the performance hints.
7764 */
7765 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7766
7767 return true;
7768 }
7769
7770 /*
7771 * Try and locate an idle core/thread in the LLC cache domain.
7772 */
select_idle_sibling(struct task_struct * p,int prev,int target)7773 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7774 {
7775 bool has_idle_core = false;
7776 struct sched_domain *sd;
7777 unsigned long task_util, util_min, util_max;
7778 int i, recent_used_cpu, prev_aff = -1;
7779
7780 /*
7781 * On asymmetric system, update task utilization because we will check
7782 * that the task fits with CPU's capacity.
7783 */
7784 if (sched_asym_cpucap_active()) {
7785 sync_entity_load_avg(&p->se);
7786 task_util = task_util_est(p);
7787 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7788 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7789 }
7790
7791 /*
7792 * per-cpu select_rq_mask usage
7793 */
7794 lockdep_assert_irqs_disabled();
7795
7796 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7797 asym_fits_cpu(task_util, util_min, util_max, target))
7798 return target;
7799
7800 /*
7801 * If the previous CPU is cache affine and idle, don't be stupid:
7802 */
7803 if (prev != target && cpus_share_cache(prev, target) &&
7804 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7805 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7806
7807 if (!static_branch_unlikely(&sched_cluster_active) ||
7808 cpus_share_resources(prev, target))
7809 return prev;
7810
7811 prev_aff = prev;
7812 }
7813
7814 /*
7815 * Allow a per-cpu kthread to stack with the wakee if the
7816 * kworker thread and the tasks previous CPUs are the same.
7817 * The assumption is that the wakee queued work for the
7818 * per-cpu kthread that is now complete and the wakeup is
7819 * essentially a sync wakeup. An obvious example of this
7820 * pattern is IO completions.
7821 */
7822 if (is_per_cpu_kthread(current) &&
7823 in_task() &&
7824 prev == smp_processor_id() &&
7825 this_rq()->nr_running <= 1 &&
7826 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7827 return prev;
7828 }
7829
7830 /* Check a recently used CPU as a potential idle candidate: */
7831 recent_used_cpu = p->recent_used_cpu;
7832 p->recent_used_cpu = prev;
7833 if (recent_used_cpu != prev &&
7834 recent_used_cpu != target &&
7835 cpus_share_cache(recent_used_cpu, target) &&
7836 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7837 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7838 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7839
7840 if (!static_branch_unlikely(&sched_cluster_active) ||
7841 cpus_share_resources(recent_used_cpu, target))
7842 return recent_used_cpu;
7843
7844 } else {
7845 recent_used_cpu = -1;
7846 }
7847
7848 /*
7849 * For asymmetric CPU capacity systems, our domain of interest is
7850 * sd_asym_cpucapacity rather than sd_llc.
7851 */
7852 if (sched_asym_cpucap_active()) {
7853 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7854 /*
7855 * On an asymmetric CPU capacity system where an exclusive
7856 * cpuset defines a symmetric island (i.e. one unique
7857 * capacity_orig value through the cpuset), the key will be set
7858 * but the CPUs within that cpuset will not have a domain with
7859 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7860 * capacity path.
7861 */
7862 if (sd) {
7863 i = select_idle_capacity(p, sd, target);
7864 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7865 }
7866 }
7867
7868 sd = rcu_dereference(per_cpu(sd_llc, target));
7869 if (!sd)
7870 return target;
7871
7872 if (sched_smt_active()) {
7873 has_idle_core = test_idle_cores(target);
7874
7875 if (!has_idle_core && cpus_share_cache(prev, target)) {
7876 i = select_idle_smt(p, sd, prev);
7877 if ((unsigned int)i < nr_cpumask_bits)
7878 return i;
7879 }
7880 }
7881
7882 i = select_idle_cpu(p, sd, has_idle_core, target);
7883 if ((unsigned)i < nr_cpumask_bits)
7884 return i;
7885
7886 /*
7887 * For cluster machines which have lower sharing cache like L2 or
7888 * LLC Tag, we tend to find an idle CPU in the target's cluster
7889 * first. But prev_cpu or recent_used_cpu may also be a good candidate,
7890 * use them if possible when no idle CPU found in select_idle_cpu().
7891 */
7892 if ((unsigned int)prev_aff < nr_cpumask_bits)
7893 return prev_aff;
7894 if ((unsigned int)recent_used_cpu < nr_cpumask_bits)
7895 return recent_used_cpu;
7896
7897 return target;
7898 }
7899
7900 /**
7901 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7902 * @cpu: the CPU to get the utilization for
7903 * @p: task for which the CPU utilization should be predicted or NULL
7904 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7905 * @boost: 1 to enable boosting, otherwise 0
7906 *
7907 * The unit of the return value must be the same as the one of CPU capacity
7908 * so that CPU utilization can be compared with CPU capacity.
7909 *
7910 * CPU utilization is the sum of running time of runnable tasks plus the
7911 * recent utilization of currently non-runnable tasks on that CPU.
7912 * It represents the amount of CPU capacity currently used by CFS tasks in
7913 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7914 * capacity at f_max.
7915 *
7916 * The estimated CPU utilization is defined as the maximum between CPU
7917 * utilization and sum of the estimated utilization of the currently
7918 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7919 * previously-executed tasks, which helps better deduce how busy a CPU will
7920 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7921 * of such a task would be significantly decayed at this point of time.
7922 *
7923 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7924 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7925 * utilization. Boosting is implemented in cpu_util() so that internal
7926 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7927 * latter via cpu_util_cfs_boost().
7928 *
7929 * CPU utilization can be higher than the current CPU capacity
7930 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7931 * of rounding errors as well as task migrations or wakeups of new tasks.
7932 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7933 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7934 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7935 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7936 * though since this is useful for predicting the CPU capacity required
7937 * after task migrations (scheduler-driven DVFS).
7938 *
7939 * Return: (Boosted) (estimated) utilization for the specified CPU.
7940 */
7941 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)7942 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7943 {
7944 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7945 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7946 unsigned long runnable;
7947
7948 if (boost) {
7949 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7950 util = max(util, runnable);
7951 }
7952
7953 /*
7954 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7955 * contribution. If @p migrates from another CPU to @cpu add its
7956 * contribution. In all the other cases @cpu is not impacted by the
7957 * migration so its util_avg is already correct.
7958 */
7959 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7960 lsub_positive(&util, task_util(p));
7961 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7962 util += task_util(p);
7963
7964 if (sched_feat(UTIL_EST)) {
7965 unsigned long util_est;
7966
7967 util_est = READ_ONCE(cfs_rq->avg.util_est);
7968
7969 /*
7970 * During wake-up @p isn't enqueued yet and doesn't contribute
7971 * to any cpu_rq(cpu)->cfs.avg.util_est.
7972 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7973 * has been enqueued.
7974 *
7975 * During exec (@dst_cpu = -1) @p is enqueued and does
7976 * contribute to cpu_rq(cpu)->cfs.util_est.
7977 * Remove it to "simulate" cpu_util without @p's contribution.
7978 *
7979 * Despite the task_on_rq_queued(@p) check there is still a
7980 * small window for a possible race when an exec
7981 * select_task_rq_fair() races with LB's detach_task().
7982 *
7983 * detach_task()
7984 * deactivate_task()
7985 * p->on_rq = TASK_ON_RQ_MIGRATING;
7986 * -------------------------------- A
7987 * dequeue_task() \
7988 * dequeue_task_fair() + Race Time
7989 * util_est_dequeue() /
7990 * -------------------------------- B
7991 *
7992 * The additional check "current == p" is required to further
7993 * reduce the race window.
7994 */
7995 if (dst_cpu == cpu)
7996 util_est += _task_util_est(p);
7997 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7998 lsub_positive(&util_est, _task_util_est(p));
7999
8000 util = max(util, util_est);
8001 }
8002
8003 return min(util, arch_scale_cpu_capacity(cpu));
8004 }
8005
cpu_util_cfs(int cpu)8006 unsigned long cpu_util_cfs(int cpu)
8007 {
8008 return cpu_util(cpu, NULL, -1, 0);
8009 }
8010
cpu_util_cfs_boost(int cpu)8011 unsigned long cpu_util_cfs_boost(int cpu)
8012 {
8013 return cpu_util(cpu, NULL, -1, 1);
8014 }
8015
8016 /*
8017 * cpu_util_without: compute cpu utilization without any contributions from *p
8018 * @cpu: the CPU which utilization is requested
8019 * @p: the task which utilization should be discounted
8020 *
8021 * The utilization of a CPU is defined by the utilization of tasks currently
8022 * enqueued on that CPU as well as tasks which are currently sleeping after an
8023 * execution on that CPU.
8024 *
8025 * This method returns the utilization of the specified CPU by discounting the
8026 * utilization of the specified task, whenever the task is currently
8027 * contributing to the CPU utilization.
8028 */
cpu_util_without(int cpu,struct task_struct * p)8029 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
8030 {
8031 /* Task has no contribution or is new */
8032 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
8033 p = NULL;
8034
8035 return cpu_util(cpu, p, -1, 0);
8036 }
8037
8038 /*
8039 * This function computes an effective utilization for the given CPU, to be
8040 * used for frequency selection given the linear relation: f = u * f_max.
8041 *
8042 * The scheduler tracks the following metrics:
8043 *
8044 * cpu_util_{cfs,rt,dl,irq}()
8045 * cpu_bw_dl()
8046 *
8047 * Where the cfs,rt and dl util numbers are tracked with the same metric and
8048 * synchronized windows and are thus directly comparable.
8049 *
8050 * The cfs,rt,dl utilization are the running times measured with rq->clock_task
8051 * which excludes things like IRQ and steal-time. These latter are then accrued
8052 * in the IRQ utilization.
8053 *
8054 * The DL bandwidth number OTOH is not a measured metric but a value computed
8055 * based on the task model parameters and gives the minimal utilization
8056 * required to meet deadlines.
8057 */
effective_cpu_util(int cpu,unsigned long util_cfs,unsigned long * min,unsigned long * max)8058 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs,
8059 unsigned long *min,
8060 unsigned long *max)
8061 {
8062 unsigned long util, irq, scale;
8063 struct rq *rq = cpu_rq(cpu);
8064
8065 scale = arch_scale_cpu_capacity(cpu);
8066
8067 /*
8068 * Early check to see if IRQ/steal time saturates the CPU, can be
8069 * because of inaccuracies in how we track these -- see
8070 * update_irq_load_avg().
8071 */
8072 irq = cpu_util_irq(rq);
8073 if (unlikely(irq >= scale)) {
8074 if (min)
8075 *min = scale;
8076 if (max)
8077 *max = scale;
8078 return scale;
8079 }
8080
8081 if (min) {
8082 /*
8083 * The minimum utilization returns the highest level between:
8084 * - the computed DL bandwidth needed with the IRQ pressure which
8085 * steals time to the deadline task.
8086 * - The minimum performance requirement for CFS and/or RT.
8087 */
8088 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN));
8089
8090 /*
8091 * When an RT task is runnable and uclamp is not used, we must
8092 * ensure that the task will run at maximum compute capacity.
8093 */
8094 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt))
8095 *min = max(*min, scale);
8096 }
8097
8098 /*
8099 * Because the time spend on RT/DL tasks is visible as 'lost' time to
8100 * CFS tasks and we use the same metric to track the effective
8101 * utilization (PELT windows are synchronized) we can directly add them
8102 * to obtain the CPU's actual utilization.
8103 */
8104 util = util_cfs + cpu_util_rt(rq);
8105 util += cpu_util_dl(rq);
8106
8107 /*
8108 * The maximum hint is a soft bandwidth requirement, which can be lower
8109 * than the actual utilization because of uclamp_max requirements.
8110 */
8111 if (max)
8112 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX));
8113
8114 if (util >= scale)
8115 return scale;
8116
8117 /*
8118 * There is still idle time; further improve the number by using the
8119 * IRQ metric. Because IRQ/steal time is hidden from the task clock we
8120 * need to scale the task numbers:
8121 *
8122 * max - irq
8123 * U' = irq + --------- * U
8124 * max
8125 */
8126 util = scale_irq_capacity(util, irq, scale);
8127 util += irq;
8128
8129 return min(scale, util);
8130 }
8131
sched_cpu_util(int cpu)8132 unsigned long sched_cpu_util(int cpu)
8133 {
8134 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL);
8135 }
8136
8137 /*
8138 * energy_env - Utilization landscape for energy estimation.
8139 * @task_busy_time: Utilization contribution by the task for which we test the
8140 * placement. Given by eenv_task_busy_time().
8141 * @pd_busy_time: Utilization of the whole perf domain without the task
8142 * contribution. Given by eenv_pd_busy_time().
8143 * @cpu_cap: Maximum CPU capacity for the perf domain.
8144 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
8145 */
8146 struct energy_env {
8147 unsigned long task_busy_time;
8148 unsigned long pd_busy_time;
8149 unsigned long cpu_cap;
8150 unsigned long pd_cap;
8151 };
8152
8153 /*
8154 * Compute the task busy time for compute_energy(). This time cannot be
8155 * injected directly into effective_cpu_util() because of the IRQ scaling.
8156 * The latter only makes sense with the most recent CPUs where the task has
8157 * run.
8158 */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)8159 static inline void eenv_task_busy_time(struct energy_env *eenv,
8160 struct task_struct *p, int prev_cpu)
8161 {
8162 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
8163 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
8164
8165 if (unlikely(irq >= max_cap))
8166 busy_time = max_cap;
8167 else
8168 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
8169
8170 eenv->task_busy_time = busy_time;
8171 }
8172
8173 /*
8174 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
8175 * utilization for each @pd_cpus, it however doesn't take into account
8176 * clamping since the ratio (utilization / cpu_capacity) is already enough to
8177 * scale the EM reported power consumption at the (eventually clamped)
8178 * cpu_capacity.
8179 *
8180 * The contribution of the task @p for which we want to estimate the
8181 * energy cost is removed (by cpu_util()) and must be calculated
8182 * separately (see eenv_task_busy_time). This ensures:
8183 *
8184 * - A stable PD utilization, no matter which CPU of that PD we want to place
8185 * the task on.
8186 *
8187 * - A fair comparison between CPUs as the task contribution (task_util())
8188 * will always be the same no matter which CPU utilization we rely on
8189 * (util_avg or util_est).
8190 *
8191 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
8192 * exceed @eenv->pd_cap.
8193 */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)8194 static inline void eenv_pd_busy_time(struct energy_env *eenv,
8195 struct cpumask *pd_cpus,
8196 struct task_struct *p)
8197 {
8198 unsigned long busy_time = 0;
8199 int cpu;
8200
8201 for_each_cpu(cpu, pd_cpus) {
8202 unsigned long util = cpu_util(cpu, p, -1, 0);
8203
8204 busy_time += effective_cpu_util(cpu, util, NULL, NULL);
8205 }
8206
8207 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
8208 }
8209
8210 /*
8211 * Compute the maximum utilization for compute_energy() when the task @p
8212 * is placed on the cpu @dst_cpu.
8213 *
8214 * Returns the maximum utilization among @eenv->cpus. This utilization can't
8215 * exceed @eenv->cpu_cap.
8216 */
8217 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)8218 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
8219 struct task_struct *p, int dst_cpu)
8220 {
8221 unsigned long max_util = 0;
8222 int cpu;
8223
8224 for_each_cpu(cpu, pd_cpus) {
8225 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
8226 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
8227 unsigned long eff_util, min, max;
8228
8229 /*
8230 * Performance domain frequency: utilization clamping
8231 * must be considered since it affects the selection
8232 * of the performance domain frequency.
8233 * NOTE: in case RT tasks are running, by default the min
8234 * utilization can be max OPP.
8235 */
8236 eff_util = effective_cpu_util(cpu, util, &min, &max);
8237
8238 /* Task's uclamp can modify min and max value */
8239 if (tsk && uclamp_is_used()) {
8240 min = max(min, uclamp_eff_value(p, UCLAMP_MIN));
8241
8242 /*
8243 * If there is no active max uclamp constraint,
8244 * directly use task's one, otherwise keep max.
8245 */
8246 if (uclamp_rq_is_idle(cpu_rq(cpu)))
8247 max = uclamp_eff_value(p, UCLAMP_MAX);
8248 else
8249 max = max(max, uclamp_eff_value(p, UCLAMP_MAX));
8250 }
8251
8252 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max);
8253 max_util = max(max_util, eff_util);
8254 }
8255
8256 return min(max_util, eenv->cpu_cap);
8257 }
8258
8259 /*
8260 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
8261 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
8262 * contribution is ignored.
8263 */
8264 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)8265 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
8266 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
8267 {
8268 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
8269 unsigned long busy_time = eenv->pd_busy_time;
8270 unsigned long energy;
8271
8272 if (dst_cpu >= 0)
8273 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
8274
8275 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
8276
8277 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time);
8278
8279 return energy;
8280 }
8281
8282 /*
8283 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
8284 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
8285 * spare capacity in each performance domain and uses it as a potential
8286 * candidate to execute the task. Then, it uses the Energy Model to figure
8287 * out which of the CPU candidates is the most energy-efficient.
8288 *
8289 * The rationale for this heuristic is as follows. In a performance domain,
8290 * all the most energy efficient CPU candidates (according to the Energy
8291 * Model) are those for which we'll request a low frequency. When there are
8292 * several CPUs for which the frequency request will be the same, we don't
8293 * have enough data to break the tie between them, because the Energy Model
8294 * only includes active power costs. With this model, if we assume that
8295 * frequency requests follow utilization (e.g. using schedutil), the CPU with
8296 * the maximum spare capacity in a performance domain is guaranteed to be among
8297 * the best candidates of the performance domain.
8298 *
8299 * In practice, it could be preferable from an energy standpoint to pack
8300 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
8301 * but that could also hurt our chances to go cluster idle, and we have no
8302 * ways to tell with the current Energy Model if this is actually a good
8303 * idea or not. So, find_energy_efficient_cpu() basically favors
8304 * cluster-packing, and spreading inside a cluster. That should at least be
8305 * a good thing for latency, and this is consistent with the idea that most
8306 * of the energy savings of EAS come from the asymmetry of the system, and
8307 * not so much from breaking the tie between identical CPUs. That's also the
8308 * reason why EAS is enabled in the topology code only for systems where
8309 * SD_ASYM_CPUCAPACITY is set.
8310 *
8311 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
8312 * they don't have any useful utilization data yet and it's not possible to
8313 * forecast their impact on energy consumption. Consequently, they will be
8314 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out
8315 * to be energy-inefficient in some use-cases. The alternative would be to
8316 * bias new tasks towards specific types of CPUs first, or to try to infer
8317 * their util_avg from the parent task, but those heuristics could hurt
8318 * other use-cases too. So, until someone finds a better way to solve this,
8319 * let's keep things simple by re-using the existing slow path.
8320 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)8321 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
8322 {
8323 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
8324 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
8325 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
8326 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
8327 struct root_domain *rd = this_rq()->rd;
8328 int cpu, best_energy_cpu, target = -1;
8329 int prev_fits = -1, best_fits = -1;
8330 unsigned long best_actual_cap = 0;
8331 unsigned long prev_actual_cap = 0;
8332 struct sched_domain *sd;
8333 struct perf_domain *pd;
8334 struct energy_env eenv;
8335
8336 rcu_read_lock();
8337 pd = rcu_dereference(rd->pd);
8338 if (!pd)
8339 goto unlock;
8340
8341 /*
8342 * Energy-aware wake-up happens on the lowest sched_domain starting
8343 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
8344 */
8345 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
8346 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
8347 sd = sd->parent;
8348 if (!sd)
8349 goto unlock;
8350
8351 target = prev_cpu;
8352
8353 sync_entity_load_avg(&p->se);
8354 if (!task_util_est(p) && p_util_min == 0)
8355 goto unlock;
8356
8357 eenv_task_busy_time(&eenv, p, prev_cpu);
8358
8359 for (; pd; pd = pd->next) {
8360 unsigned long util_min = p_util_min, util_max = p_util_max;
8361 unsigned long cpu_cap, cpu_actual_cap, util;
8362 long prev_spare_cap = -1, max_spare_cap = -1;
8363 unsigned long rq_util_min, rq_util_max;
8364 unsigned long cur_delta, base_energy;
8365 int max_spare_cap_cpu = -1;
8366 int fits, max_fits = -1;
8367
8368 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
8369
8370 if (cpumask_empty(cpus))
8371 continue;
8372
8373 /* Account external pressure for the energy estimation */
8374 cpu = cpumask_first(cpus);
8375 cpu_actual_cap = get_actual_cpu_capacity(cpu);
8376
8377 eenv.cpu_cap = cpu_actual_cap;
8378 eenv.pd_cap = 0;
8379
8380 for_each_cpu(cpu, cpus) {
8381 struct rq *rq = cpu_rq(cpu);
8382
8383 eenv.pd_cap += cpu_actual_cap;
8384
8385 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
8386 continue;
8387
8388 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
8389 continue;
8390
8391 util = cpu_util(cpu, p, cpu, 0);
8392 cpu_cap = capacity_of(cpu);
8393
8394 /*
8395 * Skip CPUs that cannot satisfy the capacity request.
8396 * IOW, placing the task there would make the CPU
8397 * overutilized. Take uclamp into account to see how
8398 * much capacity we can get out of the CPU; this is
8399 * aligned with sched_cpu_util().
8400 */
8401 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
8402 /*
8403 * Open code uclamp_rq_util_with() except for
8404 * the clamp() part. I.e.: apply max aggregation
8405 * only. util_fits_cpu() logic requires to
8406 * operate on non clamped util but must use the
8407 * max-aggregated uclamp_{min, max}.
8408 */
8409 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
8410 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
8411
8412 util_min = max(rq_util_min, p_util_min);
8413 util_max = max(rq_util_max, p_util_max);
8414 }
8415
8416 fits = util_fits_cpu(util, util_min, util_max, cpu);
8417 if (!fits)
8418 continue;
8419
8420 lsub_positive(&cpu_cap, util);
8421
8422 if (cpu == prev_cpu) {
8423 /* Always use prev_cpu as a candidate. */
8424 prev_spare_cap = cpu_cap;
8425 prev_fits = fits;
8426 } else if ((fits > max_fits) ||
8427 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8428 /*
8429 * Find the CPU with the maximum spare capacity
8430 * among the remaining CPUs in the performance
8431 * domain.
8432 */
8433 max_spare_cap = cpu_cap;
8434 max_spare_cap_cpu = cpu;
8435 max_fits = fits;
8436 }
8437 }
8438
8439 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8440 continue;
8441
8442 eenv_pd_busy_time(&eenv, cpus, p);
8443 /* Compute the 'base' energy of the pd, without @p */
8444 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8445
8446 /* Evaluate the energy impact of using prev_cpu. */
8447 if (prev_spare_cap > -1) {
8448 prev_delta = compute_energy(&eenv, pd, cpus, p,
8449 prev_cpu);
8450 /* CPU utilization has changed */
8451 if (prev_delta < base_energy)
8452 goto unlock;
8453 prev_delta -= base_energy;
8454 prev_actual_cap = cpu_actual_cap;
8455 best_delta = min(best_delta, prev_delta);
8456 }
8457
8458 /* Evaluate the energy impact of using max_spare_cap_cpu. */
8459 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8460 /* Current best energy cpu fits better */
8461 if (max_fits < best_fits)
8462 continue;
8463
8464 /*
8465 * Both don't fit performance hint (i.e. uclamp_min)
8466 * but best energy cpu has better capacity.
8467 */
8468 if ((max_fits < 0) &&
8469 (cpu_actual_cap <= best_actual_cap))
8470 continue;
8471
8472 cur_delta = compute_energy(&eenv, pd, cpus, p,
8473 max_spare_cap_cpu);
8474 /* CPU utilization has changed */
8475 if (cur_delta < base_energy)
8476 goto unlock;
8477 cur_delta -= base_energy;
8478
8479 /*
8480 * Both fit for the task but best energy cpu has lower
8481 * energy impact.
8482 */
8483 if ((max_fits > 0) && (best_fits > 0) &&
8484 (cur_delta >= best_delta))
8485 continue;
8486
8487 best_delta = cur_delta;
8488 best_energy_cpu = max_spare_cap_cpu;
8489 best_fits = max_fits;
8490 best_actual_cap = cpu_actual_cap;
8491 }
8492 }
8493 rcu_read_unlock();
8494
8495 if ((best_fits > prev_fits) ||
8496 ((best_fits > 0) && (best_delta < prev_delta)) ||
8497 ((best_fits < 0) && (best_actual_cap > prev_actual_cap)))
8498 target = best_energy_cpu;
8499
8500 return target;
8501
8502 unlock:
8503 rcu_read_unlock();
8504
8505 return target;
8506 }
8507
8508 /*
8509 * select_task_rq_fair: Select target runqueue for the waking task in domains
8510 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8511 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8512 *
8513 * Balances load by selecting the idlest CPU in the idlest group, or under
8514 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8515 *
8516 * Returns the target CPU number.
8517 */
8518 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8519 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8520 {
8521 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8522 struct sched_domain *tmp, *sd = NULL;
8523 int cpu = smp_processor_id();
8524 int new_cpu = prev_cpu;
8525 int want_affine = 0;
8526 /* SD_flags and WF_flags share the first nibble */
8527 int sd_flag = wake_flags & 0xF;
8528
8529 /*
8530 * required for stable ->cpus_allowed
8531 */
8532 lockdep_assert_held(&p->pi_lock);
8533 if (wake_flags & WF_TTWU) {
8534 record_wakee(p);
8535
8536 if ((wake_flags & WF_CURRENT_CPU) &&
8537 cpumask_test_cpu(cpu, p->cpus_ptr))
8538 return cpu;
8539
8540 if (!is_rd_overutilized(this_rq()->rd)) {
8541 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8542 if (new_cpu >= 0)
8543 return new_cpu;
8544 new_cpu = prev_cpu;
8545 }
8546
8547 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8548 }
8549
8550 rcu_read_lock();
8551 for_each_domain(cpu, tmp) {
8552 /*
8553 * If both 'cpu' and 'prev_cpu' are part of this domain,
8554 * cpu is a valid SD_WAKE_AFFINE target.
8555 */
8556 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8557 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8558 if (cpu != prev_cpu)
8559 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8560
8561 sd = NULL; /* Prefer wake_affine over balance flags */
8562 break;
8563 }
8564
8565 /*
8566 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8567 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8568 * will usually go to the fast path.
8569 */
8570 if (tmp->flags & sd_flag)
8571 sd = tmp;
8572 else if (!want_affine)
8573 break;
8574 }
8575
8576 if (unlikely(sd)) {
8577 /* Slow path */
8578 new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag);
8579 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
8580 /* Fast path */
8581 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8582 }
8583 rcu_read_unlock();
8584
8585 return new_cpu;
8586 }
8587
8588 /*
8589 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8590 * cfs_rq_of(p) references at time of call are still valid and identify the
8591 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8592 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8593 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8594 {
8595 struct sched_entity *se = &p->se;
8596
8597 if (!task_on_rq_migrating(p)) {
8598 remove_entity_load_avg(se);
8599
8600 /*
8601 * Here, the task's PELT values have been updated according to
8602 * the current rq's clock. But if that clock hasn't been
8603 * updated in a while, a substantial idle time will be missed,
8604 * leading to an inflation after wake-up on the new rq.
8605 *
8606 * Estimate the missing time from the cfs_rq last_update_time
8607 * and update sched_avg to improve the PELT continuity after
8608 * migration.
8609 */
8610 migrate_se_pelt_lag(se);
8611 }
8612
8613 /* Tell new CPU we are migrated */
8614 se->avg.last_update_time = 0;
8615
8616 update_scan_period(p, new_cpu);
8617 }
8618
task_dead_fair(struct task_struct * p)8619 static void task_dead_fair(struct task_struct *p)
8620 {
8621 struct sched_entity *se = &p->se;
8622
8623 if (se->sched_delayed) {
8624 struct rq_flags rf;
8625 struct rq *rq;
8626
8627 rq = task_rq_lock(p, &rf);
8628 if (se->sched_delayed) {
8629 update_rq_clock(rq);
8630 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
8631 }
8632 task_rq_unlock(rq, p, &rf);
8633 }
8634
8635 remove_entity_load_avg(se);
8636 }
8637
8638 /*
8639 * Set the max capacity the task is allowed to run at for misfit detection.
8640 */
set_task_max_allowed_capacity(struct task_struct * p)8641 static void set_task_max_allowed_capacity(struct task_struct *p)
8642 {
8643 struct asym_cap_data *entry;
8644
8645 if (!sched_asym_cpucap_active())
8646 return;
8647
8648 rcu_read_lock();
8649 list_for_each_entry_rcu(entry, &asym_cap_list, link) {
8650 cpumask_t *cpumask;
8651
8652 cpumask = cpu_capacity_span(entry);
8653 if (!cpumask_intersects(p->cpus_ptr, cpumask))
8654 continue;
8655
8656 p->max_allowed_capacity = entry->capacity;
8657 break;
8658 }
8659 rcu_read_unlock();
8660 }
8661
set_cpus_allowed_fair(struct task_struct * p,struct affinity_context * ctx)8662 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx)
8663 {
8664 set_cpus_allowed_common(p, ctx);
8665 set_task_max_allowed_capacity(p);
8666 }
8667
set_next_buddy(struct sched_entity * se)8668 static void set_next_buddy(struct sched_entity *se)
8669 {
8670 for_each_sched_entity(se) {
8671 if (WARN_ON_ONCE(!se->on_rq))
8672 return;
8673 if (se_is_idle(se))
8674 return;
8675 cfs_rq_of(se)->next = se;
8676 }
8677 }
8678
8679 enum preempt_wakeup_action {
8680 PREEMPT_WAKEUP_NONE, /* No preemption. */
8681 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */
8682 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */
8683 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */
8684 };
8685
8686 static inline bool
set_preempt_buddy(struct cfs_rq * cfs_rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8687 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags,
8688 struct sched_entity *pse, struct sched_entity *se)
8689 {
8690 /*
8691 * Keep existing buddy if the deadline is sooner than pse.
8692 * The older buddy may be cache cold and completely unrelated
8693 * to the current wakeup but that is unpredictable where as
8694 * obeying the deadline is more in line with EEVDF objectives.
8695 */
8696 if (cfs_rq->next && entity_before(cfs_rq->next, pse))
8697 return false;
8698
8699 set_next_buddy(pse);
8700 return true;
8701 }
8702
8703 /*
8704 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not
8705 * strictly enforced because the hint is either misunderstood or
8706 * multiple tasks must be woken up.
8707 */
8708 static inline enum preempt_wakeup_action
preempt_sync(struct rq * rq,int wake_flags,struct sched_entity * pse,struct sched_entity * se)8709 preempt_sync(struct rq *rq, int wake_flags,
8710 struct sched_entity *pse, struct sched_entity *se)
8711 {
8712 u64 threshold, delta;
8713
8714 /*
8715 * WF_SYNC without WF_TTWU is not expected so warn if it happens even
8716 * though it is likely harmless.
8717 */
8718 WARN_ON_ONCE(!(wake_flags & WF_TTWU));
8719
8720 threshold = sysctl_sched_migration_cost;
8721 delta = rq_clock_task(rq) - se->exec_start;
8722 if ((s64)delta < 0)
8723 delta = 0;
8724
8725 /*
8726 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they
8727 * could run on other CPUs. Reduce the threshold before preemption is
8728 * allowed to an arbitrary lower value as it is more likely (but not
8729 * guaranteed) the waker requires the wakee to finish.
8730 */
8731 if (wake_flags & WF_RQ_SELECTED)
8732 threshold >>= 2;
8733
8734 /*
8735 * As WF_SYNC is not strictly obeyed, allow some runtime for batch
8736 * wakeups to be issued.
8737 */
8738 if (entity_before(pse, se) && delta >= threshold)
8739 return PREEMPT_WAKEUP_RESCHED;
8740
8741 return PREEMPT_WAKEUP_NONE;
8742 }
8743
8744 /*
8745 * Preempt the current task with a newly woken task if needed:
8746 */
check_preempt_wakeup_fair(struct rq * rq,struct task_struct * p,int wake_flags)8747 static void check_preempt_wakeup_fair(struct rq *rq, struct task_struct *p, int wake_flags)
8748 {
8749 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK;
8750 struct task_struct *donor = rq->donor;
8751 struct sched_entity *se = &donor->se, *pse = &p->se;
8752 struct cfs_rq *cfs_rq = task_cfs_rq(donor);
8753 int cse_is_idle, pse_is_idle;
8754
8755 if (unlikely(se == pse))
8756 return;
8757
8758 /*
8759 * This is possible from callers such as attach_tasks(), in which we
8760 * unconditionally wakeup_preempt() after an enqueue (which may have
8761 * lead to a throttle). This both saves work and prevents false
8762 * next-buddy nomination below.
8763 */
8764 if (task_is_throttled(p))
8765 return;
8766
8767 /*
8768 * We can come here with TIF_NEED_RESCHED already set from new task
8769 * wake up path.
8770 *
8771 * Note: this also catches the edge-case of curr being in a throttled
8772 * group (e.g. via set_curr_task), since update_curr() (in the
8773 * enqueue of curr) will have resulted in resched being set. This
8774 * prevents us from potentially nominating it as a false LAST_BUDDY
8775 * below.
8776 */
8777 if (test_tsk_need_resched(rq->curr))
8778 return;
8779
8780 if (!sched_feat(WAKEUP_PREEMPTION))
8781 return;
8782
8783 find_matching_se(&se, &pse);
8784 WARN_ON_ONCE(!pse);
8785
8786 cse_is_idle = se_is_idle(se);
8787 pse_is_idle = se_is_idle(pse);
8788
8789 /*
8790 * Preempt an idle entity in favor of a non-idle entity (and don't preempt
8791 * in the inverse case).
8792 */
8793 if (cse_is_idle && !pse_is_idle) {
8794 /*
8795 * When non-idle entity preempt an idle entity,
8796 * don't give idle entity slice protection.
8797 */
8798 preempt_action = PREEMPT_WAKEUP_SHORT;
8799 goto preempt;
8800 }
8801
8802 if (cse_is_idle != pse_is_idle)
8803 return;
8804
8805 /*
8806 * BATCH and IDLE tasks do not preempt others.
8807 */
8808 if (unlikely(!normal_policy(p->policy)))
8809 return;
8810
8811 cfs_rq = cfs_rq_of(se);
8812 update_curr(cfs_rq);
8813 /*
8814 * If @p has a shorter slice than current and @p is eligible, override
8815 * current's slice protection in order to allow preemption.
8816 */
8817 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) {
8818 preempt_action = PREEMPT_WAKEUP_SHORT;
8819 goto pick;
8820 }
8821
8822 /*
8823 * Ignore wakee preemption on WF_FORK as it is less likely that
8824 * there is shared data as exec often follow fork. Do not
8825 * preempt for tasks that are sched_delayed as it would violate
8826 * EEVDF to forcibly queue an ineligible task.
8827 */
8828 if ((wake_flags & WF_FORK) || pse->sched_delayed)
8829 return;
8830
8831 /*
8832 * If @p potentially is completing work required by current then
8833 * consider preemption.
8834 *
8835 * Reschedule if waker is no longer eligible. */
8836 if (in_task() && !entity_eligible(cfs_rq, se)) {
8837 preempt_action = PREEMPT_WAKEUP_RESCHED;
8838 goto preempt;
8839 }
8840
8841 /* Prefer picking wakee soon if appropriate. */
8842 if (sched_feat(NEXT_BUDDY) &&
8843 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) {
8844
8845 /*
8846 * Decide whether to obey WF_SYNC hint for a new buddy. Old
8847 * buddies are ignored as they may not be relevant to the
8848 * waker and less likely to be cache hot.
8849 */
8850 if (wake_flags & WF_SYNC)
8851 preempt_action = preempt_sync(rq, wake_flags, pse, se);
8852 }
8853
8854 switch (preempt_action) {
8855 case PREEMPT_WAKEUP_NONE:
8856 return;
8857 case PREEMPT_WAKEUP_RESCHED:
8858 goto preempt;
8859 case PREEMPT_WAKEUP_SHORT:
8860 fallthrough;
8861 case PREEMPT_WAKEUP_PICK:
8862 break;
8863 }
8864
8865 pick:
8866 /*
8867 * If @p has become the most eligible task, force preemption.
8868 */
8869 if (__pick_eevdf(cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT) == pse)
8870 goto preempt;
8871
8872 if (sched_feat(RUN_TO_PARITY))
8873 update_protect_slice(cfs_rq, se);
8874
8875 return;
8876
8877 preempt:
8878 if (preempt_action == PREEMPT_WAKEUP_SHORT)
8879 cancel_protect_slice(se);
8880
8881 resched_curr_lazy(rq);
8882 }
8883
pick_task_fair(struct rq * rq,struct rq_flags * rf)8884 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf)
8885 {
8886 struct sched_entity *se;
8887 struct cfs_rq *cfs_rq;
8888 struct task_struct *p;
8889 bool throttled;
8890
8891 again:
8892 cfs_rq = &rq->cfs;
8893 if (!cfs_rq->nr_queued)
8894 return NULL;
8895
8896 throttled = false;
8897
8898 do {
8899 /* Might not have done put_prev_entity() */
8900 if (cfs_rq->curr && cfs_rq->curr->on_rq)
8901 update_curr(cfs_rq);
8902
8903 throttled |= check_cfs_rq_runtime(cfs_rq);
8904
8905 se = pick_next_entity(rq, cfs_rq);
8906 if (!se)
8907 goto again;
8908 cfs_rq = group_cfs_rq(se);
8909 } while (cfs_rq);
8910
8911 p = task_of(se);
8912 if (unlikely(throttled))
8913 task_throttle_setup_work(p);
8914 return p;
8915 }
8916
8917 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8918 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first);
8919
8920 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8921 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8922 {
8923 struct sched_entity *se;
8924 struct task_struct *p;
8925 int new_tasks;
8926
8927 again:
8928 p = pick_task_fair(rq, rf);
8929 if (!p)
8930 goto idle;
8931 se = &p->se;
8932
8933 #ifdef CONFIG_FAIR_GROUP_SCHED
8934 if (prev->sched_class != &fair_sched_class)
8935 goto simple;
8936
8937 __put_prev_set_next_dl_server(rq, prev, p);
8938
8939 /*
8940 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8941 * likely that a next task is from the same cgroup as the current.
8942 *
8943 * Therefore attempt to avoid putting and setting the entire cgroup
8944 * hierarchy, only change the part that actually changes.
8945 *
8946 * Since we haven't yet done put_prev_entity and if the selected task
8947 * is a different task than we started out with, try and touch the
8948 * least amount of cfs_rqs.
8949 */
8950 if (prev != p) {
8951 struct sched_entity *pse = &prev->se;
8952 struct cfs_rq *cfs_rq;
8953
8954 while (!(cfs_rq = is_same_group(se, pse))) {
8955 int se_depth = se->depth;
8956 int pse_depth = pse->depth;
8957
8958 if (se_depth <= pse_depth) {
8959 put_prev_entity(cfs_rq_of(pse), pse);
8960 pse = parent_entity(pse);
8961 }
8962 if (se_depth >= pse_depth) {
8963 set_next_entity(cfs_rq_of(se), se);
8964 se = parent_entity(se);
8965 }
8966 }
8967
8968 put_prev_entity(cfs_rq, pse);
8969 set_next_entity(cfs_rq, se);
8970
8971 __set_next_task_fair(rq, p, true);
8972 }
8973
8974 return p;
8975
8976 simple:
8977 #endif /* CONFIG_FAIR_GROUP_SCHED */
8978 put_prev_set_next_task(rq, prev, p);
8979 return p;
8980
8981 idle:
8982 if (rf) {
8983 new_tasks = sched_balance_newidle(rq, rf);
8984
8985 /*
8986 * Because sched_balance_newidle() releases (and re-acquires)
8987 * rq->lock, it is possible for any higher priority task to
8988 * appear. In that case we must re-start the pick_next_entity()
8989 * loop.
8990 */
8991 if (new_tasks < 0)
8992 return RETRY_TASK;
8993
8994 if (new_tasks > 0)
8995 goto again;
8996 }
8997
8998 /*
8999 * rq is about to be idle, check if we need to update the
9000 * lost_idle_time of clock_pelt
9001 */
9002 update_idle_rq_clock_pelt(rq);
9003
9004 return NULL;
9005 }
9006
9007 static struct task_struct *
fair_server_pick_task(struct sched_dl_entity * dl_se,struct rq_flags * rf)9008 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf)
9009 {
9010 return pick_task_fair(dl_se->rq, rf);
9011 }
9012
fair_server_init(struct rq * rq)9013 void fair_server_init(struct rq *rq)
9014 {
9015 struct sched_dl_entity *dl_se = &rq->fair_server;
9016
9017 init_dl_entity(dl_se);
9018
9019 dl_server_init(dl_se, rq, fair_server_pick_task);
9020 }
9021
9022 /*
9023 * Account for a descheduled task:
9024 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev,struct task_struct * next)9025 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next)
9026 {
9027 struct sched_entity *se = &prev->se;
9028 struct cfs_rq *cfs_rq;
9029
9030 for_each_sched_entity(se) {
9031 cfs_rq = cfs_rq_of(se);
9032 put_prev_entity(cfs_rq, se);
9033 }
9034 }
9035
9036 /*
9037 * sched_yield() is very simple
9038 */
yield_task_fair(struct rq * rq)9039 static void yield_task_fair(struct rq *rq)
9040 {
9041 struct task_struct *curr = rq->donor;
9042 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
9043 struct sched_entity *se = &curr->se;
9044
9045 /*
9046 * Are we the only task in the tree?
9047 */
9048 if (unlikely(rq->nr_running == 1))
9049 return;
9050
9051 clear_buddies(cfs_rq, se);
9052
9053 update_rq_clock(rq);
9054 /*
9055 * Update run-time statistics of the 'current'.
9056 */
9057 update_curr(cfs_rq);
9058 /*
9059 * Tell update_rq_clock() that we've just updated,
9060 * so we don't do microscopic update in schedule()
9061 * and double the fastpath cost.
9062 */
9063 rq_clock_skip_update(rq);
9064
9065 /*
9066 * Forfeit the remaining vruntime, only if the entity is eligible. This
9067 * condition is necessary because in core scheduling we prefer to run
9068 * ineligible tasks rather than force idling. If this happens we may
9069 * end up in a loop where the core scheduler picks the yielding task,
9070 * which yields immediately again; without the condition the vruntime
9071 * ends up quickly running away.
9072 */
9073 if (entity_eligible(cfs_rq, se)) {
9074 se->vruntime = se->deadline;
9075 se->deadline += calc_delta_fair(se->slice, se);
9076 }
9077 }
9078
yield_to_task_fair(struct rq * rq,struct task_struct * p)9079 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
9080 {
9081 struct sched_entity *se = &p->se;
9082
9083 /* !se->on_rq also covers throttled task */
9084 if (!se->on_rq)
9085 return false;
9086
9087 /* Tell the scheduler that we'd really like se to run next. */
9088 set_next_buddy(se);
9089
9090 yield_task_fair(rq);
9091
9092 return true;
9093 }
9094
9095 /**************************************************
9096 * Fair scheduling class load-balancing methods.
9097 *
9098 * BASICS
9099 *
9100 * The purpose of load-balancing is to achieve the same basic fairness the
9101 * per-CPU scheduler provides, namely provide a proportional amount of compute
9102 * time to each task. This is expressed in the following equation:
9103 *
9104 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
9105 *
9106 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
9107 * W_i,0 is defined as:
9108 *
9109 * W_i,0 = \Sum_j w_i,j (2)
9110 *
9111 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
9112 * is derived from the nice value as per sched_prio_to_weight[].
9113 *
9114 * The weight average is an exponential decay average of the instantaneous
9115 * weight:
9116 *
9117 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
9118 *
9119 * C_i is the compute capacity of CPU i, typically it is the
9120 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
9121 * can also include other factors [XXX].
9122 *
9123 * To achieve this balance we define a measure of imbalance which follows
9124 * directly from (1):
9125 *
9126 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
9127 *
9128 * We them move tasks around to minimize the imbalance. In the continuous
9129 * function space it is obvious this converges, in the discrete case we get
9130 * a few fun cases generally called infeasible weight scenarios.
9131 *
9132 * [XXX expand on:
9133 * - infeasible weights;
9134 * - local vs global optima in the discrete case. ]
9135 *
9136 *
9137 * SCHED DOMAINS
9138 *
9139 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
9140 * for all i,j solution, we create a tree of CPUs that follows the hardware
9141 * topology where each level pairs two lower groups (or better). This results
9142 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
9143 * tree to only the first of the previous level and we decrease the frequency
9144 * of load-balance at each level inversely proportional to the number of CPUs in
9145 * the groups.
9146 *
9147 * This yields:
9148 *
9149 * log_2 n 1 n
9150 * \Sum { --- * --- * 2^i } = O(n) (5)
9151 * i = 0 2^i 2^i
9152 * `- size of each group
9153 * | | `- number of CPUs doing load-balance
9154 * | `- freq
9155 * `- sum over all levels
9156 *
9157 * Coupled with a limit on how many tasks we can migrate every balance pass,
9158 * this makes (5) the runtime complexity of the balancer.
9159 *
9160 * An important property here is that each CPU is still (indirectly) connected
9161 * to every other CPU in at most O(log n) steps:
9162 *
9163 * The adjacency matrix of the resulting graph is given by:
9164 *
9165 * log_2 n
9166 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
9167 * k = 0
9168 *
9169 * And you'll find that:
9170 *
9171 * A^(log_2 n)_i,j != 0 for all i,j (7)
9172 *
9173 * Showing there's indeed a path between every CPU in at most O(log n) steps.
9174 * The task movement gives a factor of O(m), giving a convergence complexity
9175 * of:
9176 *
9177 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
9178 *
9179 *
9180 * WORK CONSERVING
9181 *
9182 * In order to avoid CPUs going idle while there's still work to do, new idle
9183 * balancing is more aggressive and has the newly idle CPU iterate up the domain
9184 * tree itself instead of relying on other CPUs to bring it work.
9185 *
9186 * This adds some complexity to both (5) and (8) but it reduces the total idle
9187 * time.
9188 *
9189 * [XXX more?]
9190 *
9191 *
9192 * CGROUPS
9193 *
9194 * Cgroups make a horror show out of (2), instead of a simple sum we get:
9195 *
9196 * s_k,i
9197 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
9198 * S_k
9199 *
9200 * Where
9201 *
9202 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
9203 *
9204 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
9205 *
9206 * The big problem is S_k, its a global sum needed to compute a local (W_i)
9207 * property.
9208 *
9209 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
9210 * rewrite all of this once again.]
9211 */
9212
9213 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
9214
9215 enum fbq_type { regular, remote, all };
9216
9217 /*
9218 * 'group_type' describes the group of CPUs at the moment of load balancing.
9219 *
9220 * The enum is ordered by pulling priority, with the group with lowest priority
9221 * first so the group_type can simply be compared when selecting the busiest
9222 * group. See update_sd_pick_busiest().
9223 */
9224 enum group_type {
9225 /* The group has spare capacity that can be used to run more tasks. */
9226 group_has_spare = 0,
9227 /*
9228 * The group is fully used and the tasks don't compete for more CPU
9229 * cycles. Nevertheless, some tasks might wait before running.
9230 */
9231 group_fully_busy,
9232 /*
9233 * One task doesn't fit with CPU's capacity and must be migrated to a
9234 * more powerful CPU.
9235 */
9236 group_misfit_task,
9237 /*
9238 * Balance SMT group that's fully busy. Can benefit from migration
9239 * a task on SMT with busy sibling to another CPU on idle core.
9240 */
9241 group_smt_balance,
9242 /*
9243 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
9244 * and the task should be migrated to it instead of running on the
9245 * current CPU.
9246 */
9247 group_asym_packing,
9248 /*
9249 * The tasks' affinity constraints previously prevented the scheduler
9250 * from balancing the load across the system.
9251 */
9252 group_imbalanced,
9253 /*
9254 * The CPU is overloaded and can't provide expected CPU cycles to all
9255 * tasks.
9256 */
9257 group_overloaded
9258 };
9259
9260 enum migration_type {
9261 migrate_load = 0,
9262 migrate_util,
9263 migrate_task,
9264 migrate_misfit
9265 };
9266
9267 #define LBF_ALL_PINNED 0x01
9268 #define LBF_NEED_BREAK 0x02
9269 #define LBF_DST_PINNED 0x04
9270 #define LBF_SOME_PINNED 0x08
9271 #define LBF_ACTIVE_LB 0x10
9272
9273 struct lb_env {
9274 struct sched_domain *sd;
9275
9276 struct rq *src_rq;
9277 int src_cpu;
9278
9279 int dst_cpu;
9280 struct rq *dst_rq;
9281
9282 struct cpumask *dst_grpmask;
9283 int new_dst_cpu;
9284 enum cpu_idle_type idle;
9285 long imbalance;
9286 /* The set of CPUs under consideration for load-balancing */
9287 struct cpumask *cpus;
9288
9289 unsigned int flags;
9290
9291 unsigned int loop;
9292 unsigned int loop_break;
9293 unsigned int loop_max;
9294
9295 enum fbq_type fbq_type;
9296 enum migration_type migration_type;
9297 struct list_head tasks;
9298 };
9299
9300 /*
9301 * Is this task likely cache-hot:
9302 */
task_hot(struct task_struct * p,struct lb_env * env)9303 static int task_hot(struct task_struct *p, struct lb_env *env)
9304 {
9305 s64 delta;
9306
9307 lockdep_assert_rq_held(env->src_rq);
9308
9309 if (p->sched_class != &fair_sched_class)
9310 return 0;
9311
9312 if (unlikely(task_has_idle_policy(p)))
9313 return 0;
9314
9315 /* SMT siblings share cache */
9316 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
9317 return 0;
9318
9319 /*
9320 * Buddy candidates are cache hot:
9321 */
9322 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
9323 (&p->se == cfs_rq_of(&p->se)->next))
9324 return 1;
9325
9326 if (sysctl_sched_migration_cost == -1)
9327 return 1;
9328
9329 /*
9330 * Don't migrate task if the task's cookie does not match
9331 * with the destination CPU's core cookie.
9332 */
9333 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
9334 return 1;
9335
9336 if (sysctl_sched_migration_cost == 0)
9337 return 0;
9338
9339 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
9340
9341 return delta < (s64)sysctl_sched_migration_cost;
9342 }
9343
9344 #ifdef CONFIG_NUMA_BALANCING
9345 /*
9346 * Returns a positive value, if task migration degrades locality.
9347 * Returns 0, if task migration is not affected by locality.
9348 * Returns a negative value, if task migration improves locality i.e migration preferred.
9349 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9350 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
9351 {
9352 struct numa_group *numa_group = rcu_dereference(p->numa_group);
9353 unsigned long src_weight, dst_weight;
9354 int src_nid, dst_nid, dist;
9355
9356 if (!static_branch_likely(&sched_numa_balancing))
9357 return 0;
9358
9359 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
9360 return 0;
9361
9362 src_nid = cpu_to_node(env->src_cpu);
9363 dst_nid = cpu_to_node(env->dst_cpu);
9364
9365 if (src_nid == dst_nid)
9366 return 0;
9367
9368 /* Migrating away from the preferred node is always bad. */
9369 if (src_nid == p->numa_preferred_nid) {
9370 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
9371 return 1;
9372 else
9373 return 0;
9374 }
9375
9376 /* Encourage migration to the preferred node. */
9377 if (dst_nid == p->numa_preferred_nid)
9378 return -1;
9379
9380 /* Leaving a core idle is often worse than degrading locality. */
9381 if (env->idle == CPU_IDLE)
9382 return 0;
9383
9384 dist = node_distance(src_nid, dst_nid);
9385 if (numa_group) {
9386 src_weight = group_weight(p, src_nid, dist);
9387 dst_weight = group_weight(p, dst_nid, dist);
9388 } else {
9389 src_weight = task_weight(p, src_nid, dist);
9390 dst_weight = task_weight(p, dst_nid, dist);
9391 }
9392
9393 return src_weight - dst_weight;
9394 }
9395
9396 #else /* !CONFIG_NUMA_BALANCING: */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)9397 static inline long migrate_degrades_locality(struct task_struct *p,
9398 struct lb_env *env)
9399 {
9400 return 0;
9401 }
9402 #endif /* !CONFIG_NUMA_BALANCING */
9403
9404 /*
9405 * Check whether the task is ineligible on the destination cpu
9406 *
9407 * When the PLACE_LAG scheduling feature is enabled and
9408 * dst_cfs_rq->nr_queued is greater than 1, if the task
9409 * is ineligible, it will also be ineligible when
9410 * it is migrated to the destination cpu.
9411 */
task_is_ineligible_on_dst_cpu(struct task_struct * p,int dest_cpu)9412 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu)
9413 {
9414 struct cfs_rq *dst_cfs_rq;
9415
9416 #ifdef CONFIG_FAIR_GROUP_SCHED
9417 dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu];
9418 #else
9419 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs;
9420 #endif
9421 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued &&
9422 !entity_eligible(task_cfs_rq(p), &p->se))
9423 return 1;
9424
9425 return 0;
9426 }
9427
9428 /*
9429 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
9430 */
9431 static
can_migrate_task(struct task_struct * p,struct lb_env * env)9432 int can_migrate_task(struct task_struct *p, struct lb_env *env)
9433 {
9434 long degrades, hot;
9435
9436 lockdep_assert_rq_held(env->src_rq);
9437 if (p->sched_task_hot)
9438 p->sched_task_hot = 0;
9439
9440 /*
9441 * We do not migrate tasks that are:
9442 * 1) delayed dequeued unless we migrate load, or
9443 * 2) target cfs_rq is in throttled hierarchy, or
9444 * 3) cannot be migrated to this CPU due to cpus_ptr, or
9445 * 4) running (obviously), or
9446 * 5) are cache-hot on their current CPU, or
9447 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled)
9448 */
9449 if ((p->se.sched_delayed) && (env->migration_type != migrate_load))
9450 return 0;
9451
9452 if (lb_throttled_hierarchy(p, env->dst_cpu))
9453 return 0;
9454
9455 /*
9456 * We want to prioritize the migration of eligible tasks.
9457 * For ineligible tasks we soft-limit them and only allow
9458 * them to migrate when nr_balance_failed is non-zero to
9459 * avoid load-balancing trying very hard to balance the load.
9460 */
9461 if (!env->sd->nr_balance_failed &&
9462 task_is_ineligible_on_dst_cpu(p, env->dst_cpu))
9463 return 0;
9464
9465 /* Disregard percpu kthreads; they are where they need to be. */
9466 if (kthread_is_per_cpu(p))
9467 return 0;
9468
9469 if (task_is_blocked(p))
9470 return 0;
9471
9472 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
9473 int cpu;
9474
9475 schedstat_inc(p->stats.nr_failed_migrations_affine);
9476
9477 env->flags |= LBF_SOME_PINNED;
9478
9479 /*
9480 * Remember if this task can be migrated to any other CPU in
9481 * our sched_group. We may want to revisit it if we couldn't
9482 * meet load balance goals by pulling other tasks on src_cpu.
9483 *
9484 * Avoid computing new_dst_cpu
9485 * - for NEWLY_IDLE
9486 * - if we have already computed one in current iteration
9487 * - if it's an active balance
9488 */
9489 if (env->idle == CPU_NEWLY_IDLE ||
9490 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
9491 return 0;
9492
9493 /* Prevent to re-select dst_cpu via env's CPUs: */
9494 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr);
9495
9496 if (cpu < nr_cpu_ids) {
9497 env->flags |= LBF_DST_PINNED;
9498 env->new_dst_cpu = cpu;
9499 }
9500
9501 return 0;
9502 }
9503
9504 /* Record that we found at least one task that could run on dst_cpu */
9505 env->flags &= ~LBF_ALL_PINNED;
9506
9507 if (task_on_cpu(env->src_rq, p) ||
9508 task_current_donor(env->src_rq, p)) {
9509 schedstat_inc(p->stats.nr_failed_migrations_running);
9510 return 0;
9511 }
9512
9513 /*
9514 * Aggressive migration if:
9515 * 1) active balance
9516 * 2) destination numa is preferred
9517 * 3) task is cache cold, or
9518 * 4) too many balance attempts have failed.
9519 */
9520 if (env->flags & LBF_ACTIVE_LB)
9521 return 1;
9522
9523 degrades = migrate_degrades_locality(p, env);
9524 if (!degrades)
9525 hot = task_hot(p, env);
9526 else
9527 hot = degrades > 0;
9528
9529 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9530 if (hot)
9531 p->sched_task_hot = 1;
9532 return 1;
9533 }
9534
9535 schedstat_inc(p->stats.nr_failed_migrations_hot);
9536 return 0;
9537 }
9538
9539 /*
9540 * detach_task() -- detach the task for the migration specified in env
9541 */
detach_task(struct task_struct * p,struct lb_env * env)9542 static void detach_task(struct task_struct *p, struct lb_env *env)
9543 {
9544 lockdep_assert_rq_held(env->src_rq);
9545
9546 if (p->sched_task_hot) {
9547 p->sched_task_hot = 0;
9548 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9549 schedstat_inc(p->stats.nr_forced_migrations);
9550 }
9551
9552 WARN_ON(task_current(env->src_rq, p));
9553 WARN_ON(task_current_donor(env->src_rq, p));
9554
9555 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9556 set_task_cpu(p, env->dst_cpu);
9557 }
9558
9559 /*
9560 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9561 * part of active balancing operations within "domain".
9562 *
9563 * Returns a task if successful and NULL otherwise.
9564 */
detach_one_task(struct lb_env * env)9565 static struct task_struct *detach_one_task(struct lb_env *env)
9566 {
9567 struct task_struct *p;
9568
9569 lockdep_assert_rq_held(env->src_rq);
9570
9571 list_for_each_entry_reverse(p,
9572 &env->src_rq->cfs_tasks, se.group_node) {
9573 if (!can_migrate_task(p, env))
9574 continue;
9575
9576 detach_task(p, env);
9577
9578 /*
9579 * Right now, this is only the second place where
9580 * lb_gained[env->idle] is updated (other is detach_tasks)
9581 * so we can safely collect stats here rather than
9582 * inside detach_tasks().
9583 */
9584 schedstat_inc(env->sd->lb_gained[env->idle]);
9585 return p;
9586 }
9587 return NULL;
9588 }
9589
9590 /*
9591 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9592 * busiest_rq, as part of a balancing operation within domain "sd".
9593 *
9594 * Returns number of detached tasks if successful and 0 otherwise.
9595 */
detach_tasks(struct lb_env * env)9596 static int detach_tasks(struct lb_env *env)
9597 {
9598 struct list_head *tasks = &env->src_rq->cfs_tasks;
9599 unsigned long util, load;
9600 struct task_struct *p;
9601 int detached = 0;
9602
9603 lockdep_assert_rq_held(env->src_rq);
9604
9605 /*
9606 * Source run queue has been emptied by another CPU, clear
9607 * LBF_ALL_PINNED flag as we will not test any task.
9608 */
9609 if (env->src_rq->nr_running <= 1) {
9610 env->flags &= ~LBF_ALL_PINNED;
9611 return 0;
9612 }
9613
9614 if (env->imbalance <= 0)
9615 return 0;
9616
9617 while (!list_empty(tasks)) {
9618 /*
9619 * We don't want to steal all, otherwise we may be treated likewise,
9620 * which could at worst lead to a livelock crash.
9621 */
9622 if (env->idle && env->src_rq->nr_running <= 1)
9623 break;
9624
9625 env->loop++;
9626 /* We've more or less seen every task there is, call it quits */
9627 if (env->loop > env->loop_max)
9628 break;
9629
9630 /* take a breather every nr_migrate tasks */
9631 if (env->loop > env->loop_break) {
9632 env->loop_break += SCHED_NR_MIGRATE_BREAK;
9633 env->flags |= LBF_NEED_BREAK;
9634 break;
9635 }
9636
9637 p = list_last_entry(tasks, struct task_struct, se.group_node);
9638
9639 if (!can_migrate_task(p, env))
9640 goto next;
9641
9642 switch (env->migration_type) {
9643 case migrate_load:
9644 /*
9645 * Depending of the number of CPUs and tasks and the
9646 * cgroup hierarchy, task_h_load() can return a null
9647 * value. Make sure that env->imbalance decreases
9648 * otherwise detach_tasks() will stop only after
9649 * detaching up to loop_max tasks.
9650 */
9651 load = max_t(unsigned long, task_h_load(p), 1);
9652
9653 if (sched_feat(LB_MIN) &&
9654 load < 16 && !env->sd->nr_balance_failed)
9655 goto next;
9656
9657 /*
9658 * Make sure that we don't migrate too much load.
9659 * Nevertheless, let relax the constraint if
9660 * scheduler fails to find a good waiting task to
9661 * migrate.
9662 */
9663 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9664 goto next;
9665
9666 env->imbalance -= load;
9667 break;
9668
9669 case migrate_util:
9670 util = task_util_est(p);
9671
9672 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance)
9673 goto next;
9674
9675 env->imbalance -= util;
9676 break;
9677
9678 case migrate_task:
9679 env->imbalance--;
9680 break;
9681
9682 case migrate_misfit:
9683 /* This is not a misfit task */
9684 if (task_fits_cpu(p, env->src_cpu))
9685 goto next;
9686
9687 env->imbalance = 0;
9688 break;
9689 }
9690
9691 detach_task(p, env);
9692 list_add(&p->se.group_node, &env->tasks);
9693
9694 detached++;
9695
9696 #ifdef CONFIG_PREEMPTION
9697 /*
9698 * NEWIDLE balancing is a source of latency, so preemptible
9699 * kernels will stop after the first task is detached to minimize
9700 * the critical section.
9701 */
9702 if (env->idle == CPU_NEWLY_IDLE)
9703 break;
9704 #endif
9705
9706 /*
9707 * We only want to steal up to the prescribed amount of
9708 * load/util/tasks.
9709 */
9710 if (env->imbalance <= 0)
9711 break;
9712
9713 continue;
9714 next:
9715 if (p->sched_task_hot)
9716 schedstat_inc(p->stats.nr_failed_migrations_hot);
9717
9718 list_move(&p->se.group_node, tasks);
9719 }
9720
9721 /*
9722 * Right now, this is one of only two places we collect this stat
9723 * so we can safely collect detach_one_task() stats here rather
9724 * than inside detach_one_task().
9725 */
9726 schedstat_add(env->sd->lb_gained[env->idle], detached);
9727
9728 return detached;
9729 }
9730
9731 /*
9732 * attach_task() -- attach the task detached by detach_task() to its new rq.
9733 */
attach_task(struct rq * rq,struct task_struct * p)9734 static void attach_task(struct rq *rq, struct task_struct *p)
9735 {
9736 lockdep_assert_rq_held(rq);
9737
9738 WARN_ON_ONCE(task_rq(p) != rq);
9739 activate_task(rq, p, ENQUEUE_NOCLOCK);
9740 wakeup_preempt(rq, p, 0);
9741 }
9742
9743 /*
9744 * attach_one_task() -- attaches the task returned from detach_one_task() to
9745 * its new rq.
9746 */
attach_one_task(struct rq * rq,struct task_struct * p)9747 static void attach_one_task(struct rq *rq, struct task_struct *p)
9748 {
9749 struct rq_flags rf;
9750
9751 rq_lock(rq, &rf);
9752 update_rq_clock(rq);
9753 attach_task(rq, p);
9754 rq_unlock(rq, &rf);
9755 }
9756
9757 /*
9758 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9759 * new rq.
9760 */
attach_tasks(struct lb_env * env)9761 static void attach_tasks(struct lb_env *env)
9762 {
9763 struct list_head *tasks = &env->tasks;
9764 struct task_struct *p;
9765 struct rq_flags rf;
9766
9767 rq_lock(env->dst_rq, &rf);
9768 update_rq_clock(env->dst_rq);
9769
9770 while (!list_empty(tasks)) {
9771 p = list_first_entry(tasks, struct task_struct, se.group_node);
9772 list_del_init(&p->se.group_node);
9773
9774 attach_task(env->dst_rq, p);
9775 }
9776
9777 rq_unlock(env->dst_rq, &rf);
9778 }
9779
9780 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9781 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9782 {
9783 if (cfs_rq->avg.load_avg)
9784 return true;
9785
9786 if (cfs_rq->avg.util_avg)
9787 return true;
9788
9789 return false;
9790 }
9791
others_have_blocked(struct rq * rq)9792 static inline bool others_have_blocked(struct rq *rq)
9793 {
9794 if (cpu_util_rt(rq))
9795 return true;
9796
9797 if (cpu_util_dl(rq))
9798 return true;
9799
9800 if (hw_load_avg(rq))
9801 return true;
9802
9803 if (cpu_util_irq(rq))
9804 return true;
9805
9806 return false;
9807 }
9808
update_blocked_load_tick(struct rq * rq)9809 static inline void update_blocked_load_tick(struct rq *rq)
9810 {
9811 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9812 }
9813
update_blocked_load_status(struct rq * rq,bool has_blocked)9814 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9815 {
9816 if (!has_blocked)
9817 rq->has_blocked_load = 0;
9818 }
9819 #else /* !CONFIG_NO_HZ_COMMON: */
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9820 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)9821 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)9822 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)9823 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9824 #endif /* !CONFIG_NO_HZ_COMMON */
9825
__update_blocked_others(struct rq * rq,bool * done)9826 static bool __update_blocked_others(struct rq *rq, bool *done)
9827 {
9828 bool updated;
9829
9830 /*
9831 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9832 * DL and IRQ signals have been updated before updating CFS.
9833 */
9834 updated = update_other_load_avgs(rq);
9835
9836 if (others_have_blocked(rq))
9837 *done = false;
9838
9839 return updated;
9840 }
9841
9842 #ifdef CONFIG_FAIR_GROUP_SCHED
9843
__update_blocked_fair(struct rq * rq,bool * done)9844 static bool __update_blocked_fair(struct rq *rq, bool *done)
9845 {
9846 struct cfs_rq *cfs_rq, *pos;
9847 bool decayed = false;
9848 int cpu = cpu_of(rq);
9849
9850 /*
9851 * Iterates the task_group tree in a bottom up fashion, see
9852 * list_add_leaf_cfs_rq() for details.
9853 */
9854 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9855 struct sched_entity *se;
9856
9857 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9858 update_tg_load_avg(cfs_rq);
9859
9860 if (cfs_rq->nr_queued == 0)
9861 update_idle_cfs_rq_clock_pelt(cfs_rq);
9862
9863 if (cfs_rq == &rq->cfs)
9864 decayed = true;
9865 }
9866
9867 /* Propagate pending load changes to the parent, if any: */
9868 se = cfs_rq->tg->se[cpu];
9869 if (se && !skip_blocked_update(se))
9870 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9871
9872 /*
9873 * There can be a lot of idle CPU cgroups. Don't let fully
9874 * decayed cfs_rqs linger on the list.
9875 */
9876 if (cfs_rq_is_decayed(cfs_rq))
9877 list_del_leaf_cfs_rq(cfs_rq);
9878
9879 /* Don't need periodic decay once load/util_avg are null */
9880 if (cfs_rq_has_blocked(cfs_rq))
9881 *done = false;
9882 }
9883
9884 return decayed;
9885 }
9886
9887 /*
9888 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9889 * This needs to be done in a top-down fashion because the load of a child
9890 * group is a fraction of its parents load.
9891 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)9892 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9893 {
9894 struct rq *rq = rq_of(cfs_rq);
9895 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9896 unsigned long now = jiffies;
9897 unsigned long load;
9898
9899 if (cfs_rq->last_h_load_update == now)
9900 return;
9901
9902 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9903 for_each_sched_entity(se) {
9904 cfs_rq = cfs_rq_of(se);
9905 WRITE_ONCE(cfs_rq->h_load_next, se);
9906 if (cfs_rq->last_h_load_update == now)
9907 break;
9908 }
9909
9910 if (!se) {
9911 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9912 cfs_rq->last_h_load_update = now;
9913 }
9914
9915 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9916 load = cfs_rq->h_load;
9917 load = div64_ul(load * se->avg.load_avg,
9918 cfs_rq_load_avg(cfs_rq) + 1);
9919 cfs_rq = group_cfs_rq(se);
9920 cfs_rq->h_load = load;
9921 cfs_rq->last_h_load_update = now;
9922 }
9923 }
9924
task_h_load(struct task_struct * p)9925 static unsigned long task_h_load(struct task_struct *p)
9926 {
9927 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9928
9929 update_cfs_rq_h_load(cfs_rq);
9930 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9931 cfs_rq_load_avg(cfs_rq) + 1);
9932 }
9933 #else /* !CONFIG_FAIR_GROUP_SCHED: */
__update_blocked_fair(struct rq * rq,bool * done)9934 static bool __update_blocked_fair(struct rq *rq, bool *done)
9935 {
9936 struct cfs_rq *cfs_rq = &rq->cfs;
9937 bool decayed;
9938
9939 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9940 if (cfs_rq_has_blocked(cfs_rq))
9941 *done = false;
9942
9943 return decayed;
9944 }
9945
task_h_load(struct task_struct * p)9946 static unsigned long task_h_load(struct task_struct *p)
9947 {
9948 return p->se.avg.load_avg;
9949 }
9950 #endif /* !CONFIG_FAIR_GROUP_SCHED */
9951
sched_balance_update_blocked_averages(int cpu)9952 static void sched_balance_update_blocked_averages(int cpu)
9953 {
9954 bool decayed = false, done = true;
9955 struct rq *rq = cpu_rq(cpu);
9956 struct rq_flags rf;
9957
9958 rq_lock_irqsave(rq, &rf);
9959 update_blocked_load_tick(rq);
9960 update_rq_clock(rq);
9961
9962 decayed |= __update_blocked_others(rq, &done);
9963 decayed |= __update_blocked_fair(rq, &done);
9964
9965 update_blocked_load_status(rq, !done);
9966 if (decayed)
9967 cpufreq_update_util(rq, 0);
9968 rq_unlock_irqrestore(rq, &rf);
9969 }
9970
9971 /********** Helpers for sched_balance_find_src_group ************************/
9972
9973 /*
9974 * sg_lb_stats - stats of a sched_group required for load-balancing:
9975 */
9976 struct sg_lb_stats {
9977 unsigned long avg_load; /* Avg load over the CPUs of the group */
9978 unsigned long group_load; /* Total load over the CPUs of the group */
9979 unsigned long group_capacity; /* Capacity over the CPUs of the group */
9980 unsigned long group_util; /* Total utilization over the CPUs of the group */
9981 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9982 unsigned int sum_nr_running; /* Nr of all tasks running in the group */
9983 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9984 unsigned int idle_cpus; /* Nr of idle CPUs in the group */
9985 unsigned int group_weight;
9986 enum group_type group_type;
9987 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9988 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9989 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9990 #ifdef CONFIG_NUMA_BALANCING
9991 unsigned int nr_numa_running;
9992 unsigned int nr_preferred_running;
9993 #endif
9994 };
9995
9996 /*
9997 * sd_lb_stats - stats of a sched_domain required for load-balancing:
9998 */
9999 struct sd_lb_stats {
10000 struct sched_group *busiest; /* Busiest group in this sd */
10001 struct sched_group *local; /* Local group in this sd */
10002 unsigned long total_load; /* Total load of all groups in sd */
10003 unsigned long total_capacity; /* Total capacity of all groups in sd */
10004 unsigned long avg_load; /* Average load across all groups in sd */
10005 unsigned int prefer_sibling; /* Tasks should go to sibling first */
10006
10007 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */
10008 struct sg_lb_stats local_stat; /* Statistics of the local group */
10009 };
10010
init_sd_lb_stats(struct sd_lb_stats * sds)10011 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
10012 {
10013 /*
10014 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
10015 * local_stat because update_sg_lb_stats() does a full clear/assignment.
10016 * We must however set busiest_stat::group_type and
10017 * busiest_stat::idle_cpus to the worst busiest group because
10018 * update_sd_pick_busiest() reads these before assignment.
10019 */
10020 *sds = (struct sd_lb_stats){
10021 .busiest = NULL,
10022 .local = NULL,
10023 .total_load = 0UL,
10024 .total_capacity = 0UL,
10025 .busiest_stat = {
10026 .idle_cpus = UINT_MAX,
10027 .group_type = group_has_spare,
10028 },
10029 };
10030 }
10031
scale_rt_capacity(int cpu)10032 static unsigned long scale_rt_capacity(int cpu)
10033 {
10034 unsigned long max = get_actual_cpu_capacity(cpu);
10035 struct rq *rq = cpu_rq(cpu);
10036 unsigned long used, free;
10037 unsigned long irq;
10038
10039 irq = cpu_util_irq(rq);
10040
10041 if (unlikely(irq >= max))
10042 return 1;
10043
10044 /*
10045 * avg_rt.util_avg and avg_dl.util_avg track binary signals
10046 * (running and not running) with weights 0 and 1024 respectively.
10047 */
10048 used = cpu_util_rt(rq);
10049 used += cpu_util_dl(rq);
10050
10051 if (unlikely(used >= max))
10052 return 1;
10053
10054 free = max - used;
10055
10056 return scale_irq_capacity(free, irq, max);
10057 }
10058
update_cpu_capacity(struct sched_domain * sd,int cpu)10059 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
10060 {
10061 unsigned long capacity = scale_rt_capacity(cpu);
10062 struct sched_group *sdg = sd->groups;
10063
10064 if (!capacity)
10065 capacity = 1;
10066
10067 cpu_rq(cpu)->cpu_capacity = capacity;
10068 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
10069
10070 sdg->sgc->capacity = capacity;
10071 sdg->sgc->min_capacity = capacity;
10072 sdg->sgc->max_capacity = capacity;
10073 }
10074
update_group_capacity(struct sched_domain * sd,int cpu)10075 void update_group_capacity(struct sched_domain *sd, int cpu)
10076 {
10077 struct sched_domain *child = sd->child;
10078 struct sched_group *group, *sdg = sd->groups;
10079 unsigned long capacity, min_capacity, max_capacity;
10080 unsigned long interval;
10081
10082 interval = msecs_to_jiffies(sd->balance_interval);
10083 interval = clamp(interval, 1UL, max_load_balance_interval);
10084 sdg->sgc->next_update = jiffies + interval;
10085
10086 if (!child) {
10087 update_cpu_capacity(sd, cpu);
10088 return;
10089 }
10090
10091 capacity = 0;
10092 min_capacity = ULONG_MAX;
10093 max_capacity = 0;
10094
10095 if (child->flags & SD_NUMA) {
10096 /*
10097 * SD_NUMA domains cannot assume that child groups
10098 * span the current group.
10099 */
10100
10101 for_each_cpu(cpu, sched_group_span(sdg)) {
10102 unsigned long cpu_cap = capacity_of(cpu);
10103
10104 capacity += cpu_cap;
10105 min_capacity = min(cpu_cap, min_capacity);
10106 max_capacity = max(cpu_cap, max_capacity);
10107 }
10108 } else {
10109 /*
10110 * !SD_NUMA domains can assume that child groups
10111 * span the current group.
10112 */
10113
10114 group = child->groups;
10115 do {
10116 struct sched_group_capacity *sgc = group->sgc;
10117
10118 capacity += sgc->capacity;
10119 min_capacity = min(sgc->min_capacity, min_capacity);
10120 max_capacity = max(sgc->max_capacity, max_capacity);
10121 group = group->next;
10122 } while (group != child->groups);
10123 }
10124
10125 sdg->sgc->capacity = capacity;
10126 sdg->sgc->min_capacity = min_capacity;
10127 sdg->sgc->max_capacity = max_capacity;
10128 }
10129
10130 /*
10131 * Check whether the capacity of the rq has been noticeably reduced by side
10132 * activity. The imbalance_pct is used for the threshold.
10133 * Return true is the capacity is reduced
10134 */
10135 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)10136 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
10137 {
10138 return ((rq->cpu_capacity * sd->imbalance_pct) <
10139 (arch_scale_cpu_capacity(cpu_of(rq)) * 100));
10140 }
10141
10142 /* Check if the rq has a misfit task */
check_misfit_status(struct rq * rq)10143 static inline bool check_misfit_status(struct rq *rq)
10144 {
10145 return rq->misfit_task_load;
10146 }
10147
10148 /*
10149 * Group imbalance indicates (and tries to solve) the problem where balancing
10150 * groups is inadequate due to ->cpus_ptr constraints.
10151 *
10152 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
10153 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
10154 * Something like:
10155 *
10156 * { 0 1 2 3 } { 4 5 6 7 }
10157 * * * * *
10158 *
10159 * If we were to balance group-wise we'd place two tasks in the first group and
10160 * two tasks in the second group. Clearly this is undesired as it will overload
10161 * cpu 3 and leave one of the CPUs in the second group unused.
10162 *
10163 * The current solution to this issue is detecting the skew in the first group
10164 * by noticing the lower domain failed to reach balance and had difficulty
10165 * moving tasks due to affinity constraints.
10166 *
10167 * When this is so detected; this group becomes a candidate for busiest; see
10168 * update_sd_pick_busiest(). And calculate_imbalance() and
10169 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it
10170 * to create an effective group imbalance.
10171 *
10172 * This is a somewhat tricky proposition since the next run might not find the
10173 * group imbalance and decide the groups need to be balanced again. A most
10174 * subtle and fragile situation.
10175 */
10176
sg_imbalanced(struct sched_group * group)10177 static inline int sg_imbalanced(struct sched_group *group)
10178 {
10179 return group->sgc->imbalance;
10180 }
10181
10182 /*
10183 * group_has_capacity returns true if the group has spare capacity that could
10184 * be used by some tasks.
10185 * We consider that a group has spare capacity if the number of task is
10186 * smaller than the number of CPUs or if the utilization is lower than the
10187 * available capacity for CFS tasks.
10188 * For the latter, we use a threshold to stabilize the state, to take into
10189 * account the variance of the tasks' load and to return true if the available
10190 * capacity in meaningful for the load balancer.
10191 * As an example, an available capacity of 1% can appear but it doesn't make
10192 * any benefit for the load balance.
10193 */
10194 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10195 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10196 {
10197 if (sgs->sum_nr_running < sgs->group_weight)
10198 return true;
10199
10200 if ((sgs->group_capacity * imbalance_pct) <
10201 (sgs->group_runnable * 100))
10202 return false;
10203
10204 if ((sgs->group_capacity * 100) >
10205 (sgs->group_util * imbalance_pct))
10206 return true;
10207
10208 return false;
10209 }
10210
10211 /*
10212 * group_is_overloaded returns true if the group has more tasks than it can
10213 * handle.
10214 * group_is_overloaded is not equals to !group_has_capacity because a group
10215 * with the exact right number of tasks, has no more spare capacity but is not
10216 * overloaded so both group_has_capacity and group_is_overloaded return
10217 * false.
10218 */
10219 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)10220 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
10221 {
10222 if (sgs->sum_nr_running <= sgs->group_weight)
10223 return false;
10224
10225 if ((sgs->group_capacity * 100) <
10226 (sgs->group_util * imbalance_pct))
10227 return true;
10228
10229 if ((sgs->group_capacity * imbalance_pct) <
10230 (sgs->group_runnable * 100))
10231 return true;
10232
10233 return false;
10234 }
10235
10236 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)10237 group_type group_classify(unsigned int imbalance_pct,
10238 struct sched_group *group,
10239 struct sg_lb_stats *sgs)
10240 {
10241 if (group_is_overloaded(imbalance_pct, sgs))
10242 return group_overloaded;
10243
10244 if (sg_imbalanced(group))
10245 return group_imbalanced;
10246
10247 if (sgs->group_asym_packing)
10248 return group_asym_packing;
10249
10250 if (sgs->group_smt_balance)
10251 return group_smt_balance;
10252
10253 if (sgs->group_misfit_task_load)
10254 return group_misfit_task;
10255
10256 if (!group_has_capacity(imbalance_pct, sgs))
10257 return group_fully_busy;
10258
10259 return group_has_spare;
10260 }
10261
10262 /**
10263 * sched_use_asym_prio - Check whether asym_packing priority must be used
10264 * @sd: The scheduling domain of the load balancing
10265 * @cpu: A CPU
10266 *
10267 * Always use CPU priority when balancing load between SMT siblings. When
10268 * balancing load between cores, it is not sufficient that @cpu is idle. Only
10269 * use CPU priority if the whole core is idle.
10270 *
10271 * Returns: True if the priority of @cpu must be followed. False otherwise.
10272 */
sched_use_asym_prio(struct sched_domain * sd,int cpu)10273 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
10274 {
10275 if (!(sd->flags & SD_ASYM_PACKING))
10276 return false;
10277
10278 if (!sched_smt_active())
10279 return true;
10280
10281 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
10282 }
10283
sched_asym(struct sched_domain * sd,int dst_cpu,int src_cpu)10284 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu)
10285 {
10286 /*
10287 * First check if @dst_cpu can do asym_packing load balance. Only do it
10288 * if it has higher priority than @src_cpu.
10289 */
10290 return sched_use_asym_prio(sd, dst_cpu) &&
10291 sched_asym_prefer(dst_cpu, src_cpu);
10292 }
10293
10294 /**
10295 * sched_group_asym - Check if the destination CPU can do asym_packing balance
10296 * @env: The load balancing environment
10297 * @sgs: Load-balancing statistics of the candidate busiest group
10298 * @group: The candidate busiest group
10299 *
10300 * @env::dst_cpu can do asym_packing if it has higher priority than the
10301 * preferred CPU of @group.
10302 *
10303 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
10304 * otherwise.
10305 */
10306 static inline bool
sched_group_asym(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10307 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group)
10308 {
10309 /*
10310 * CPU priorities do not make sense for SMT cores with more than one
10311 * busy sibling.
10312 */
10313 if ((group->flags & SD_SHARE_CPUCAPACITY) &&
10314 (sgs->group_weight - sgs->idle_cpus != 1))
10315 return false;
10316
10317 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu));
10318 }
10319
10320 /* 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)10321 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
10322 struct sched_group *sg2)
10323 {
10324 if (!sg1 || !sg2)
10325 return false;
10326
10327 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
10328 (sg2->flags & SD_SHARE_CPUCAPACITY);
10329 }
10330
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)10331 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
10332 struct sched_group *group)
10333 {
10334 if (!env->idle)
10335 return false;
10336
10337 /*
10338 * For SMT source group, it is better to move a task
10339 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
10340 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
10341 * will not be on.
10342 */
10343 if (group->flags & SD_SHARE_CPUCAPACITY &&
10344 sgs->sum_h_nr_running > 1)
10345 return true;
10346
10347 return false;
10348 }
10349
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)10350 static inline long sibling_imbalance(struct lb_env *env,
10351 struct sd_lb_stats *sds,
10352 struct sg_lb_stats *busiest,
10353 struct sg_lb_stats *local)
10354 {
10355 int ncores_busiest, ncores_local;
10356 long imbalance;
10357
10358 if (!env->idle || !busiest->sum_nr_running)
10359 return 0;
10360
10361 ncores_busiest = sds->busiest->cores;
10362 ncores_local = sds->local->cores;
10363
10364 if (ncores_busiest == ncores_local) {
10365 imbalance = busiest->sum_nr_running;
10366 lsub_positive(&imbalance, local->sum_nr_running);
10367 return imbalance;
10368 }
10369
10370 /* Balance such that nr_running/ncores ratio are same on both groups */
10371 imbalance = ncores_local * busiest->sum_nr_running;
10372 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
10373 /* Normalize imbalance and do rounding on normalization */
10374 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
10375 imbalance /= ncores_local + ncores_busiest;
10376
10377 /* Take advantage of resource in an empty sched group */
10378 if (imbalance <= 1 && local->sum_nr_running == 0 &&
10379 busiest->sum_nr_running > 1)
10380 imbalance = 2;
10381
10382 return imbalance;
10383 }
10384
10385 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)10386 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
10387 {
10388 /*
10389 * When there is more than 1 task, the group_overloaded case already
10390 * takes care of cpu with reduced capacity
10391 */
10392 if (rq->cfs.h_nr_runnable != 1)
10393 return false;
10394
10395 return check_cpu_capacity(rq, sd);
10396 }
10397
10398 /**
10399 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
10400 * @env: The load balancing environment.
10401 * @sds: Load-balancing data with statistics of the local group.
10402 * @group: sched_group whose statistics are to be updated.
10403 * @sgs: variable to hold the statistics for this group.
10404 * @sg_overloaded: sched_group is overloaded
10405 * @sg_overutilized: sched_group is overutilized
10406 */
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)10407 static inline void update_sg_lb_stats(struct lb_env *env,
10408 struct sd_lb_stats *sds,
10409 struct sched_group *group,
10410 struct sg_lb_stats *sgs,
10411 bool *sg_overloaded,
10412 bool *sg_overutilized)
10413 {
10414 int i, nr_running, local_group, sd_flags = env->sd->flags;
10415 bool balancing_at_rd = !env->sd->parent;
10416
10417 memset(sgs, 0, sizeof(*sgs));
10418
10419 local_group = group == sds->local;
10420
10421 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
10422 struct rq *rq = cpu_rq(i);
10423 unsigned long load = cpu_load(rq);
10424
10425 sgs->group_load += load;
10426 sgs->group_util += cpu_util_cfs(i);
10427 sgs->group_runnable += cpu_runnable(rq);
10428 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable;
10429
10430 nr_running = rq->nr_running;
10431 sgs->sum_nr_running += nr_running;
10432
10433 if (cpu_overutilized(i))
10434 *sg_overutilized = 1;
10435
10436 /*
10437 * No need to call idle_cpu() if nr_running is not 0
10438 */
10439 if (!nr_running && idle_cpu(i)) {
10440 sgs->idle_cpus++;
10441 /* Idle cpu can't have misfit task */
10442 continue;
10443 }
10444
10445 /* Overload indicator is only updated at root domain */
10446 if (balancing_at_rd && nr_running > 1)
10447 *sg_overloaded = 1;
10448
10449 #ifdef CONFIG_NUMA_BALANCING
10450 /* Only fbq_classify_group() uses this to classify NUMA groups */
10451 if (sd_flags & SD_NUMA) {
10452 sgs->nr_numa_running += rq->nr_numa_running;
10453 sgs->nr_preferred_running += rq->nr_preferred_running;
10454 }
10455 #endif
10456 if (local_group)
10457 continue;
10458
10459 if (sd_flags & SD_ASYM_CPUCAPACITY) {
10460 /* Check for a misfit task on the cpu */
10461 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
10462 sgs->group_misfit_task_load = rq->misfit_task_load;
10463 *sg_overloaded = 1;
10464 }
10465 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) {
10466 /* Check for a task running on a CPU with reduced capacity */
10467 if (sgs->group_misfit_task_load < load)
10468 sgs->group_misfit_task_load = load;
10469 }
10470 }
10471
10472 sgs->group_capacity = group->sgc->capacity;
10473
10474 sgs->group_weight = group->group_weight;
10475
10476 /* Check if dst CPU is idle and preferred to this group */
10477 if (!local_group && env->idle && sgs->sum_h_nr_running &&
10478 sched_group_asym(env, sgs, group))
10479 sgs->group_asym_packing = 1;
10480
10481 /* Check for loaded SMT group to be balanced to dst CPU */
10482 if (!local_group && smt_balance(env, sgs, group))
10483 sgs->group_smt_balance = 1;
10484
10485 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10486
10487 /* Computing avg_load makes sense only when group is overloaded */
10488 if (sgs->group_type == group_overloaded)
10489 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10490 sgs->group_capacity;
10491 }
10492
10493 /**
10494 * update_sd_pick_busiest - return 1 on busiest group
10495 * @env: The load balancing environment.
10496 * @sds: sched_domain statistics
10497 * @sg: sched_group candidate to be checked for being the busiest
10498 * @sgs: sched_group statistics
10499 *
10500 * Determine if @sg is a busier group than the previously selected
10501 * busiest group.
10502 *
10503 * Return: %true if @sg is a busier group than the previously selected
10504 * busiest group. %false otherwise.
10505 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10506 static bool update_sd_pick_busiest(struct lb_env *env,
10507 struct sd_lb_stats *sds,
10508 struct sched_group *sg,
10509 struct sg_lb_stats *sgs)
10510 {
10511 struct sg_lb_stats *busiest = &sds->busiest_stat;
10512
10513 /* Make sure that there is at least one task to pull */
10514 if (!sgs->sum_h_nr_running)
10515 return false;
10516
10517 /*
10518 * Don't try to pull misfit tasks we can't help.
10519 * We can use max_capacity here as reduction in capacity on some
10520 * CPUs in the group should either be possible to resolve
10521 * internally or be covered by avg_load imbalance (eventually).
10522 */
10523 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10524 (sgs->group_type == group_misfit_task) &&
10525 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10526 sds->local_stat.group_type != group_has_spare))
10527 return false;
10528
10529 if (sgs->group_type > busiest->group_type)
10530 return true;
10531
10532 if (sgs->group_type < busiest->group_type)
10533 return false;
10534
10535 /*
10536 * The candidate and the current busiest group are the same type of
10537 * group. Let check which one is the busiest according to the type.
10538 */
10539
10540 switch (sgs->group_type) {
10541 case group_overloaded:
10542 /* Select the overloaded group with highest avg_load. */
10543 return sgs->avg_load > busiest->avg_load;
10544
10545 case group_imbalanced:
10546 /*
10547 * Select the 1st imbalanced group as we don't have any way to
10548 * choose one more than another.
10549 */
10550 return false;
10551
10552 case group_asym_packing:
10553 /* Prefer to move from lowest priority CPU's work */
10554 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu),
10555 READ_ONCE(sg->asym_prefer_cpu));
10556
10557 case group_misfit_task:
10558 /*
10559 * If we have more than one misfit sg go with the biggest
10560 * misfit.
10561 */
10562 return sgs->group_misfit_task_load > busiest->group_misfit_task_load;
10563
10564 case group_smt_balance:
10565 /*
10566 * Check if we have spare CPUs on either SMT group to
10567 * choose has spare or fully busy handling.
10568 */
10569 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10570 goto has_spare;
10571
10572 fallthrough;
10573
10574 case group_fully_busy:
10575 /*
10576 * Select the fully busy group with highest avg_load. In
10577 * theory, there is no need to pull task from such kind of
10578 * group because tasks have all compute capacity that they need
10579 * but we can still improve the overall throughput by reducing
10580 * contention when accessing shared HW resources.
10581 *
10582 * XXX for now avg_load is not computed and always 0 so we
10583 * select the 1st one, except if @sg is composed of SMT
10584 * siblings.
10585 */
10586
10587 if (sgs->avg_load < busiest->avg_load)
10588 return false;
10589
10590 if (sgs->avg_load == busiest->avg_load) {
10591 /*
10592 * SMT sched groups need more help than non-SMT groups.
10593 * If @sg happens to also be SMT, either choice is good.
10594 */
10595 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10596 return false;
10597 }
10598
10599 break;
10600
10601 case group_has_spare:
10602 /*
10603 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10604 * as we do not want to pull task off SMT core with one task
10605 * and make the core idle.
10606 */
10607 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10608 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10609 return false;
10610 else
10611 return true;
10612 }
10613 has_spare:
10614
10615 /*
10616 * Select not overloaded group with lowest number of idle CPUs
10617 * and highest number of running tasks. We could also compare
10618 * the spare capacity which is more stable but it can end up
10619 * that the group has less spare capacity but finally more idle
10620 * CPUs which means less opportunity to pull tasks.
10621 */
10622 if (sgs->idle_cpus > busiest->idle_cpus)
10623 return false;
10624 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10625 (sgs->sum_nr_running <= busiest->sum_nr_running))
10626 return false;
10627
10628 break;
10629 }
10630
10631 /*
10632 * Candidate sg has no more than one task per CPU and has higher
10633 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10634 * throughput. Maximize throughput, power/energy consequences are not
10635 * considered.
10636 */
10637 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10638 (sgs->group_type <= group_fully_busy) &&
10639 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10640 return false;
10641
10642 return true;
10643 }
10644
10645 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10646 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10647 {
10648 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10649 return regular;
10650 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10651 return remote;
10652 return all;
10653 }
10654
fbq_classify_rq(struct rq * rq)10655 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10656 {
10657 if (rq->nr_running > rq->nr_numa_running)
10658 return regular;
10659 if (rq->nr_running > rq->nr_preferred_running)
10660 return remote;
10661 return all;
10662 }
10663 #else /* !CONFIG_NUMA_BALANCING: */
fbq_classify_group(struct sg_lb_stats * sgs)10664 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10665 {
10666 return all;
10667 }
10668
fbq_classify_rq(struct rq * rq)10669 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10670 {
10671 return regular;
10672 }
10673 #endif /* !CONFIG_NUMA_BALANCING */
10674
10675
10676 struct sg_lb_stats;
10677
10678 /*
10679 * task_running_on_cpu - return 1 if @p is running on @cpu.
10680 */
10681
task_running_on_cpu(int cpu,struct task_struct * p)10682 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10683 {
10684 /* Task has no contribution or is new */
10685 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10686 return 0;
10687
10688 if (task_on_rq_queued(p))
10689 return 1;
10690
10691 return 0;
10692 }
10693
10694 /**
10695 * idle_cpu_without - would a given CPU be idle without p ?
10696 * @cpu: the processor on which idleness is tested.
10697 * @p: task which should be ignored.
10698 *
10699 * Return: 1 if the CPU would be idle. 0 otherwise.
10700 */
idle_cpu_without(int cpu,struct task_struct * p)10701 static int idle_cpu_without(int cpu, struct task_struct *p)
10702 {
10703 struct rq *rq = cpu_rq(cpu);
10704
10705 if (rq->curr != rq->idle && rq->curr != p)
10706 return 0;
10707
10708 /*
10709 * rq->nr_running can't be used but an updated version without the
10710 * impact of p on cpu must be used instead. The updated nr_running
10711 * be computed and tested before calling idle_cpu_without().
10712 */
10713
10714 if (rq->ttwu_pending)
10715 return 0;
10716
10717 return 1;
10718 }
10719
10720 /*
10721 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10722 * @sd: The sched_domain level to look for idlest group.
10723 * @group: sched_group whose statistics are to be updated.
10724 * @sgs: variable to hold the statistics for this group.
10725 * @p: The task for which we look for the idlest group/CPU.
10726 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10727 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10728 struct sched_group *group,
10729 struct sg_lb_stats *sgs,
10730 struct task_struct *p)
10731 {
10732 int i, nr_running;
10733
10734 memset(sgs, 0, sizeof(*sgs));
10735
10736 /* Assume that task can't fit any CPU of the group */
10737 if (sd->flags & SD_ASYM_CPUCAPACITY)
10738 sgs->group_misfit_task_load = 1;
10739
10740 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
10741 struct rq *rq = cpu_rq(i);
10742 unsigned int local;
10743
10744 sgs->group_load += cpu_load_without(rq, p);
10745 sgs->group_util += cpu_util_without(i, p);
10746 sgs->group_runnable += cpu_runnable_without(rq, p);
10747 local = task_running_on_cpu(i, p);
10748 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local;
10749
10750 nr_running = rq->nr_running - local;
10751 sgs->sum_nr_running += nr_running;
10752
10753 /*
10754 * No need to call idle_cpu_without() if nr_running is not 0
10755 */
10756 if (!nr_running && idle_cpu_without(i, p))
10757 sgs->idle_cpus++;
10758
10759 /* Check if task fits in the CPU */
10760 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10761 sgs->group_misfit_task_load &&
10762 task_fits_cpu(p, i))
10763 sgs->group_misfit_task_load = 0;
10764
10765 }
10766
10767 sgs->group_capacity = group->sgc->capacity;
10768
10769 sgs->group_weight = group->group_weight;
10770
10771 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10772
10773 /*
10774 * Computing avg_load makes sense only when group is fully busy or
10775 * overloaded
10776 */
10777 if (sgs->group_type == group_fully_busy ||
10778 sgs->group_type == group_overloaded)
10779 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10780 sgs->group_capacity;
10781 }
10782
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10783 static bool update_pick_idlest(struct sched_group *idlest,
10784 struct sg_lb_stats *idlest_sgs,
10785 struct sched_group *group,
10786 struct sg_lb_stats *sgs)
10787 {
10788 if (sgs->group_type < idlest_sgs->group_type)
10789 return true;
10790
10791 if (sgs->group_type > idlest_sgs->group_type)
10792 return false;
10793
10794 /*
10795 * The candidate and the current idlest group are the same type of
10796 * group. Let check which one is the idlest according to the type.
10797 */
10798
10799 switch (sgs->group_type) {
10800 case group_overloaded:
10801 case group_fully_busy:
10802 /* Select the group with lowest avg_load. */
10803 if (idlest_sgs->avg_load <= sgs->avg_load)
10804 return false;
10805 break;
10806
10807 case group_imbalanced:
10808 case group_asym_packing:
10809 case group_smt_balance:
10810 /* Those types are not used in the slow wakeup path */
10811 return false;
10812
10813 case group_misfit_task:
10814 /* Select group with the highest max capacity */
10815 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10816 return false;
10817 break;
10818
10819 case group_has_spare:
10820 /* Select group with most idle CPUs */
10821 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10822 return false;
10823
10824 /* Select group with lowest group_util */
10825 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10826 idlest_sgs->group_util <= sgs->group_util)
10827 return false;
10828
10829 break;
10830 }
10831
10832 return true;
10833 }
10834
10835 /*
10836 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the
10837 * domain.
10838 *
10839 * Assumes p is allowed on at least one CPU in sd.
10840 */
10841 static struct sched_group *
sched_balance_find_dst_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)10842 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10843 {
10844 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10845 struct sg_lb_stats local_sgs, tmp_sgs;
10846 struct sg_lb_stats *sgs;
10847 unsigned long imbalance;
10848 struct sg_lb_stats idlest_sgs = {
10849 .avg_load = UINT_MAX,
10850 .group_type = group_overloaded,
10851 };
10852
10853 do {
10854 int local_group;
10855
10856 /* Skip over this group if it has no CPUs allowed */
10857 if (!cpumask_intersects(sched_group_span(group),
10858 p->cpus_ptr))
10859 continue;
10860
10861 /* Skip over this group if no cookie matched */
10862 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10863 continue;
10864
10865 local_group = cpumask_test_cpu(this_cpu,
10866 sched_group_span(group));
10867
10868 if (local_group) {
10869 sgs = &local_sgs;
10870 local = group;
10871 } else {
10872 sgs = &tmp_sgs;
10873 }
10874
10875 update_sg_wakeup_stats(sd, group, sgs, p);
10876
10877 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10878 idlest = group;
10879 idlest_sgs = *sgs;
10880 }
10881
10882 } while (group = group->next, group != sd->groups);
10883
10884
10885 /* There is no idlest group to push tasks to */
10886 if (!idlest)
10887 return NULL;
10888
10889 /* The local group has been skipped because of CPU affinity */
10890 if (!local)
10891 return idlest;
10892
10893 /*
10894 * If the local group is idler than the selected idlest group
10895 * don't try and push the task.
10896 */
10897 if (local_sgs.group_type < idlest_sgs.group_type)
10898 return NULL;
10899
10900 /*
10901 * If the local group is busier than the selected idlest group
10902 * try and push the task.
10903 */
10904 if (local_sgs.group_type > idlest_sgs.group_type)
10905 return idlest;
10906
10907 switch (local_sgs.group_type) {
10908 case group_overloaded:
10909 case group_fully_busy:
10910
10911 /* Calculate allowed imbalance based on load */
10912 imbalance = scale_load_down(NICE_0_LOAD) *
10913 (sd->imbalance_pct-100) / 100;
10914
10915 /*
10916 * When comparing groups across NUMA domains, it's possible for
10917 * the local domain to be very lightly loaded relative to the
10918 * remote domains but "imbalance" skews the comparison making
10919 * remote CPUs look much more favourable. When considering
10920 * cross-domain, add imbalance to the load on the remote node
10921 * and consider staying local.
10922 */
10923
10924 if ((sd->flags & SD_NUMA) &&
10925 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10926 return NULL;
10927
10928 /*
10929 * If the local group is less loaded than the selected
10930 * idlest group don't try and push any tasks.
10931 */
10932 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10933 return NULL;
10934
10935 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10936 return NULL;
10937 break;
10938
10939 case group_imbalanced:
10940 case group_asym_packing:
10941 case group_smt_balance:
10942 /* Those type are not used in the slow wakeup path */
10943 return NULL;
10944
10945 case group_misfit_task:
10946 /* Select group with the highest max capacity */
10947 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10948 return NULL;
10949 break;
10950
10951 case group_has_spare:
10952 #ifdef CONFIG_NUMA
10953 if (sd->flags & SD_NUMA) {
10954 int imb_numa_nr = sd->imb_numa_nr;
10955 #ifdef CONFIG_NUMA_BALANCING
10956 int idlest_cpu;
10957 /*
10958 * If there is spare capacity at NUMA, try to select
10959 * the preferred node
10960 */
10961 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10962 return NULL;
10963
10964 idlest_cpu = cpumask_first(sched_group_span(idlest));
10965 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10966 return idlest;
10967 #endif /* CONFIG_NUMA_BALANCING */
10968 /*
10969 * Otherwise, keep the task close to the wakeup source
10970 * and improve locality if the number of running tasks
10971 * would remain below threshold where an imbalance is
10972 * allowed while accounting for the possibility the
10973 * task is pinned to a subset of CPUs. If there is a
10974 * real need of migration, periodic load balance will
10975 * take care of it.
10976 */
10977 if (p->nr_cpus_allowed != NR_CPUS) {
10978 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10979
10980 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10981 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10982 }
10983
10984 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10985 if (!adjust_numa_imbalance(imbalance,
10986 local_sgs.sum_nr_running + 1,
10987 imb_numa_nr)) {
10988 return NULL;
10989 }
10990 }
10991 #endif /* CONFIG_NUMA */
10992
10993 /*
10994 * Select group with highest number of idle CPUs. We could also
10995 * compare the utilization which is more stable but it can end
10996 * up that the group has less spare capacity but finally more
10997 * idle CPUs which means more opportunity to run task.
10998 */
10999 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
11000 return NULL;
11001 break;
11002 }
11003
11004 return idlest;
11005 }
11006
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)11007 static void update_idle_cpu_scan(struct lb_env *env,
11008 unsigned long sum_util)
11009 {
11010 struct sched_domain_shared *sd_share;
11011 int llc_weight, pct;
11012 u64 x, y, tmp;
11013 /*
11014 * Update the number of CPUs to scan in LLC domain, which could
11015 * be used as a hint in select_idle_cpu(). The update of sd_share
11016 * could be expensive because it is within a shared cache line.
11017 * So the write of this hint only occurs during periodic load
11018 * balancing, rather than CPU_NEWLY_IDLE, because the latter
11019 * can fire way more frequently than the former.
11020 */
11021 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
11022 return;
11023
11024 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
11025 if (env->sd->span_weight != llc_weight)
11026 return;
11027
11028 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
11029 if (!sd_share)
11030 return;
11031
11032 /*
11033 * The number of CPUs to search drops as sum_util increases, when
11034 * sum_util hits 85% or above, the scan stops.
11035 * The reason to choose 85% as the threshold is because this is the
11036 * imbalance_pct(117) when a LLC sched group is overloaded.
11037 *
11038 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
11039 * and y'= y / SCHED_CAPACITY_SCALE
11040 *
11041 * x is the ratio of sum_util compared to the CPU capacity:
11042 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
11043 * y' is the ratio of CPUs to be scanned in the LLC domain,
11044 * and the number of CPUs to scan is calculated by:
11045 *
11046 * nr_scan = llc_weight * y' [2]
11047 *
11048 * When x hits the threshold of overloaded, AKA, when
11049 * x = 100 / pct, y drops to 0. According to [1],
11050 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
11051 *
11052 * Scale x by SCHED_CAPACITY_SCALE:
11053 * x' = sum_util / llc_weight; [3]
11054 *
11055 * and finally [1] becomes:
11056 * y = SCHED_CAPACITY_SCALE -
11057 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
11058 *
11059 */
11060 /* equation [3] */
11061 x = sum_util;
11062 do_div(x, llc_weight);
11063
11064 /* equation [4] */
11065 pct = env->sd->imbalance_pct;
11066 tmp = x * x * pct * pct;
11067 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
11068 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
11069 y = SCHED_CAPACITY_SCALE - tmp;
11070
11071 /* equation [2] */
11072 y *= llc_weight;
11073 do_div(y, SCHED_CAPACITY_SCALE);
11074 if ((int)y != sd_share->nr_idle_scan)
11075 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
11076 }
11077
11078 /**
11079 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
11080 * @env: The load balancing environment.
11081 * @sds: variable to hold the statistics for this sched_domain.
11082 */
11083
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)11084 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
11085 {
11086 struct sched_group *sg = env->sd->groups;
11087 struct sg_lb_stats *local = &sds->local_stat;
11088 struct sg_lb_stats tmp_sgs;
11089 unsigned long sum_util = 0;
11090 bool sg_overloaded = 0, sg_overutilized = 0;
11091
11092 do {
11093 struct sg_lb_stats *sgs = &tmp_sgs;
11094 int local_group;
11095
11096 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
11097 if (local_group) {
11098 sds->local = sg;
11099 sgs = local;
11100
11101 if (env->idle != CPU_NEWLY_IDLE ||
11102 time_after_eq(jiffies, sg->sgc->next_update))
11103 update_group_capacity(env->sd, env->dst_cpu);
11104 }
11105
11106 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized);
11107
11108 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) {
11109 sds->busiest = sg;
11110 sds->busiest_stat = *sgs;
11111 }
11112
11113 /* Now, start updating sd_lb_stats */
11114 sds->total_load += sgs->group_load;
11115 sds->total_capacity += sgs->group_capacity;
11116
11117 sum_util += sgs->group_util;
11118 sg = sg->next;
11119 } while (sg != env->sd->groups);
11120
11121 /*
11122 * Indicate that the child domain of the busiest group prefers tasks
11123 * go to a child's sibling domains first. NB the flags of a sched group
11124 * are those of the child domain.
11125 */
11126 if (sds->busiest)
11127 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
11128
11129
11130 if (env->sd->flags & SD_NUMA)
11131 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
11132
11133 if (!env->sd->parent) {
11134 /* update overload indicator if we are at root domain */
11135 set_rd_overloaded(env->dst_rq->rd, sg_overloaded);
11136
11137 /* Update over-utilization (tipping point, U >= 0) indicator */
11138 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11139 } else if (sg_overutilized) {
11140 set_rd_overutilized(env->dst_rq->rd, sg_overutilized);
11141 }
11142
11143 update_idle_cpu_scan(env, sum_util);
11144 }
11145
11146 /**
11147 * calculate_imbalance - Calculate the amount of imbalance present within the
11148 * groups of a given sched_domain during load balance.
11149 * @env: load balance environment
11150 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
11151 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)11152 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
11153 {
11154 struct sg_lb_stats *local, *busiest;
11155
11156 local = &sds->local_stat;
11157 busiest = &sds->busiest_stat;
11158
11159 if (busiest->group_type == group_misfit_task) {
11160 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
11161 /* Set imbalance to allow misfit tasks to be balanced. */
11162 env->migration_type = migrate_misfit;
11163 env->imbalance = 1;
11164 } else {
11165 /*
11166 * Set load imbalance to allow moving task from cpu
11167 * with reduced capacity.
11168 */
11169 env->migration_type = migrate_load;
11170 env->imbalance = busiest->group_misfit_task_load;
11171 }
11172 return;
11173 }
11174
11175 if (busiest->group_type == group_asym_packing) {
11176 /*
11177 * In case of asym capacity, we will try to migrate all load to
11178 * the preferred CPU.
11179 */
11180 env->migration_type = migrate_task;
11181 env->imbalance = busiest->sum_h_nr_running;
11182 return;
11183 }
11184
11185 if (busiest->group_type == group_smt_balance) {
11186 /* Reduce number of tasks sharing CPU capacity */
11187 env->migration_type = migrate_task;
11188 env->imbalance = 1;
11189 return;
11190 }
11191
11192 if (busiest->group_type == group_imbalanced) {
11193 /*
11194 * In the group_imb case we cannot rely on group-wide averages
11195 * to ensure CPU-load equilibrium, try to move any task to fix
11196 * the imbalance. The next load balance will take care of
11197 * balancing back the system.
11198 */
11199 env->migration_type = migrate_task;
11200 env->imbalance = 1;
11201 return;
11202 }
11203
11204 /*
11205 * Try to use spare capacity of local group without overloading it or
11206 * emptying busiest.
11207 */
11208 if (local->group_type == group_has_spare) {
11209 if ((busiest->group_type > group_fully_busy) &&
11210 !(env->sd->flags & SD_SHARE_LLC)) {
11211 /*
11212 * If busiest is overloaded, try to fill spare
11213 * capacity. This might end up creating spare capacity
11214 * in busiest or busiest still being overloaded but
11215 * there is no simple way to directly compute the
11216 * amount of load to migrate in order to balance the
11217 * system.
11218 */
11219 env->migration_type = migrate_util;
11220 env->imbalance = max(local->group_capacity, local->group_util) -
11221 local->group_util;
11222
11223 /*
11224 * In some cases, the group's utilization is max or even
11225 * higher than capacity because of migrations but the
11226 * local CPU is (newly) idle. There is at least one
11227 * waiting task in this overloaded busiest group. Let's
11228 * try to pull it.
11229 */
11230 if (env->idle && env->imbalance == 0) {
11231 env->migration_type = migrate_task;
11232 env->imbalance = 1;
11233 }
11234
11235 return;
11236 }
11237
11238 if (busiest->group_weight == 1 || sds->prefer_sibling) {
11239 /*
11240 * When prefer sibling, evenly spread running tasks on
11241 * groups.
11242 */
11243 env->migration_type = migrate_task;
11244 env->imbalance = sibling_imbalance(env, sds, busiest, local);
11245 } else {
11246
11247 /*
11248 * If there is no overload, we just want to even the number of
11249 * idle CPUs.
11250 */
11251 env->migration_type = migrate_task;
11252 env->imbalance = max_t(long, 0,
11253 (local->idle_cpus - busiest->idle_cpus));
11254 }
11255
11256 #ifdef CONFIG_NUMA
11257 /* Consider allowing a small imbalance between NUMA groups */
11258 if (env->sd->flags & SD_NUMA) {
11259 env->imbalance = adjust_numa_imbalance(env->imbalance,
11260 local->sum_nr_running + 1,
11261 env->sd->imb_numa_nr);
11262 }
11263 #endif
11264
11265 /* Number of tasks to move to restore balance */
11266 env->imbalance >>= 1;
11267
11268 return;
11269 }
11270
11271 /*
11272 * Local is fully busy but has to take more load to relieve the
11273 * busiest group
11274 */
11275 if (local->group_type < group_overloaded) {
11276 /*
11277 * Local will become overloaded so the avg_load metrics are
11278 * finally needed.
11279 */
11280
11281 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
11282 local->group_capacity;
11283
11284 /*
11285 * If the local group is more loaded than the selected
11286 * busiest group don't try to pull any tasks.
11287 */
11288 if (local->avg_load >= busiest->avg_load) {
11289 env->imbalance = 0;
11290 return;
11291 }
11292
11293 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
11294 sds->total_capacity;
11295
11296 /*
11297 * If the local group is more loaded than the average system
11298 * load, don't try to pull any tasks.
11299 */
11300 if (local->avg_load >= sds->avg_load) {
11301 env->imbalance = 0;
11302 return;
11303 }
11304
11305 }
11306
11307 /*
11308 * Both group are or will become overloaded and we're trying to get all
11309 * the CPUs to the average_load, so we don't want to push ourselves
11310 * above the average load, nor do we wish to reduce the max loaded CPU
11311 * below the average load. At the same time, we also don't want to
11312 * reduce the group load below the group capacity. Thus we look for
11313 * the minimum possible imbalance.
11314 */
11315 env->migration_type = migrate_load;
11316 env->imbalance = min(
11317 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
11318 (sds->avg_load - local->avg_load) * local->group_capacity
11319 ) / SCHED_CAPACITY_SCALE;
11320 }
11321
11322 /******* sched_balance_find_src_group() helpers end here *********************/
11323
11324 /*
11325 * Decision matrix according to the local and busiest group type:
11326 *
11327 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
11328 * has_spare nr_idle balanced N/A N/A balanced balanced
11329 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
11330 * misfit_task force N/A N/A N/A N/A N/A
11331 * asym_packing force force N/A N/A force force
11332 * imbalanced force force N/A N/A force force
11333 * overloaded force force N/A N/A force avg_load
11334 *
11335 * N/A : Not Applicable because already filtered while updating
11336 * statistics.
11337 * balanced : The system is balanced for these 2 groups.
11338 * force : Calculate the imbalance as load migration is probably needed.
11339 * avg_load : Only if imbalance is significant enough.
11340 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
11341 * different in groups.
11342 */
11343
11344 /**
11345 * sched_balance_find_src_group - Returns the busiest group within the sched_domain
11346 * if there is an imbalance.
11347 * @env: The load balancing environment.
11348 *
11349 * Also calculates the amount of runnable load which should be moved
11350 * to restore balance.
11351 *
11352 * Return: - The busiest group if imbalance exists.
11353 */
sched_balance_find_src_group(struct lb_env * env)11354 static struct sched_group *sched_balance_find_src_group(struct lb_env *env)
11355 {
11356 struct sg_lb_stats *local, *busiest;
11357 struct sd_lb_stats sds;
11358
11359 init_sd_lb_stats(&sds);
11360
11361 /*
11362 * Compute the various statistics relevant for load balancing at
11363 * this level.
11364 */
11365 update_sd_lb_stats(env, &sds);
11366
11367 /* There is no busy sibling group to pull tasks from */
11368 if (!sds.busiest)
11369 goto out_balanced;
11370
11371 busiest = &sds.busiest_stat;
11372
11373 /* Misfit tasks should be dealt with regardless of the avg load */
11374 if (busiest->group_type == group_misfit_task)
11375 goto force_balance;
11376
11377 if (!is_rd_overutilized(env->dst_rq->rd) &&
11378 rcu_dereference(env->dst_rq->rd->pd))
11379 goto out_balanced;
11380
11381 /* ASYM feature bypasses nice load balance check */
11382 if (busiest->group_type == group_asym_packing)
11383 goto force_balance;
11384
11385 /*
11386 * If the busiest group is imbalanced the below checks don't
11387 * work because they assume all things are equal, which typically
11388 * isn't true due to cpus_ptr constraints and the like.
11389 */
11390 if (busiest->group_type == group_imbalanced)
11391 goto force_balance;
11392
11393 local = &sds.local_stat;
11394 /*
11395 * If the local group is busier than the selected busiest group
11396 * don't try and pull any tasks.
11397 */
11398 if (local->group_type > busiest->group_type)
11399 goto out_balanced;
11400
11401 /*
11402 * When groups are overloaded, use the avg_load to ensure fairness
11403 * between tasks.
11404 */
11405 if (local->group_type == group_overloaded) {
11406 /*
11407 * If the local group is more loaded than the selected
11408 * busiest group don't try to pull any tasks.
11409 */
11410 if (local->avg_load >= busiest->avg_load)
11411 goto out_balanced;
11412
11413 /* XXX broken for overlapping NUMA groups */
11414 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
11415 sds.total_capacity;
11416
11417 /*
11418 * Don't pull any tasks if this group is already above the
11419 * domain average load.
11420 */
11421 if (local->avg_load >= sds.avg_load)
11422 goto out_balanced;
11423
11424 /*
11425 * If the busiest group is more loaded, use imbalance_pct to be
11426 * conservative.
11427 */
11428 if (100 * busiest->avg_load <=
11429 env->sd->imbalance_pct * local->avg_load)
11430 goto out_balanced;
11431 }
11432
11433 /*
11434 * Try to move all excess tasks to a sibling domain of the busiest
11435 * group's child domain.
11436 */
11437 if (sds.prefer_sibling && local->group_type == group_has_spare &&
11438 sibling_imbalance(env, &sds, busiest, local) > 1)
11439 goto force_balance;
11440
11441 if (busiest->group_type != group_overloaded) {
11442 if (!env->idle) {
11443 /*
11444 * If the busiest group is not overloaded (and as a
11445 * result the local one too) but this CPU is already
11446 * busy, let another idle CPU try to pull task.
11447 */
11448 goto out_balanced;
11449 }
11450
11451 if (busiest->group_type == group_smt_balance &&
11452 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
11453 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
11454 goto force_balance;
11455 }
11456
11457 if (busiest->group_weight > 1 &&
11458 local->idle_cpus <= (busiest->idle_cpus + 1)) {
11459 /*
11460 * If the busiest group is not overloaded
11461 * and there is no imbalance between this and busiest
11462 * group wrt idle CPUs, it is balanced. The imbalance
11463 * becomes significant if the diff is greater than 1
11464 * otherwise we might end up to just move the imbalance
11465 * on another group. Of course this applies only if
11466 * there is more than 1 CPU per group.
11467 */
11468 goto out_balanced;
11469 }
11470
11471 if (busiest->sum_h_nr_running == 1) {
11472 /*
11473 * busiest doesn't have any tasks waiting to run
11474 */
11475 goto out_balanced;
11476 }
11477 }
11478
11479 force_balance:
11480 /* Looks like there is an imbalance. Compute it */
11481 calculate_imbalance(env, &sds);
11482 return env->imbalance ? sds.busiest : NULL;
11483
11484 out_balanced:
11485 env->imbalance = 0;
11486 return NULL;
11487 }
11488
11489 /*
11490 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group.
11491 */
sched_balance_find_src_rq(struct lb_env * env,struct sched_group * group)11492 static struct rq *sched_balance_find_src_rq(struct lb_env *env,
11493 struct sched_group *group)
11494 {
11495 struct rq *busiest = NULL, *rq;
11496 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11497 unsigned int busiest_nr = 0;
11498 int i;
11499
11500 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11501 unsigned long capacity, load, util;
11502 unsigned int nr_running;
11503 enum fbq_type rt;
11504
11505 rq = cpu_rq(i);
11506 rt = fbq_classify_rq(rq);
11507
11508 /*
11509 * We classify groups/runqueues into three groups:
11510 * - regular: there are !numa tasks
11511 * - remote: there are numa tasks that run on the 'wrong' node
11512 * - all: there is no distinction
11513 *
11514 * In order to avoid migrating ideally placed numa tasks,
11515 * ignore those when there's better options.
11516 *
11517 * If we ignore the actual busiest queue to migrate another
11518 * task, the next balance pass can still reduce the busiest
11519 * queue by moving tasks around inside the node.
11520 *
11521 * If we cannot move enough load due to this classification
11522 * the next pass will adjust the group classification and
11523 * allow migration of more tasks.
11524 *
11525 * Both cases only affect the total convergence complexity.
11526 */
11527 if (rt > env->fbq_type)
11528 continue;
11529
11530 nr_running = rq->cfs.h_nr_runnable;
11531 if (!nr_running)
11532 continue;
11533
11534 capacity = capacity_of(i);
11535
11536 /*
11537 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11538 * eventually lead to active_balancing high->low capacity.
11539 * Higher per-CPU capacity is considered better than balancing
11540 * average load.
11541 */
11542 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11543 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11544 nr_running == 1)
11545 continue;
11546
11547 /*
11548 * Make sure we only pull tasks from a CPU of lower priority
11549 * when balancing between SMT siblings.
11550 *
11551 * If balancing between cores, let lower priority CPUs help
11552 * SMT cores with more than one busy sibling.
11553 */
11554 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1)
11555 continue;
11556
11557 switch (env->migration_type) {
11558 case migrate_load:
11559 /*
11560 * When comparing with load imbalance, use cpu_load()
11561 * which is not scaled with the CPU capacity.
11562 */
11563 load = cpu_load(rq);
11564
11565 if (nr_running == 1 && load > env->imbalance &&
11566 !check_cpu_capacity(rq, env->sd))
11567 break;
11568
11569 /*
11570 * For the load comparisons with the other CPUs,
11571 * consider the cpu_load() scaled with the CPU
11572 * capacity, so that the load can be moved away
11573 * from the CPU that is potentially running at a
11574 * lower capacity.
11575 *
11576 * Thus we're looking for max(load_i / capacity_i),
11577 * crosswise multiplication to rid ourselves of the
11578 * division works out to:
11579 * load_i * capacity_j > load_j * capacity_i;
11580 * where j is our previous maximum.
11581 */
11582 if (load * busiest_capacity > busiest_load * capacity) {
11583 busiest_load = load;
11584 busiest_capacity = capacity;
11585 busiest = rq;
11586 }
11587 break;
11588
11589 case migrate_util:
11590 util = cpu_util_cfs_boost(i);
11591
11592 /*
11593 * Don't try to pull utilization from a CPU with one
11594 * running task. Whatever its utilization, we will fail
11595 * detach the task.
11596 */
11597 if (nr_running <= 1)
11598 continue;
11599
11600 if (busiest_util < util) {
11601 busiest_util = util;
11602 busiest = rq;
11603 }
11604 break;
11605
11606 case migrate_task:
11607 if (busiest_nr < nr_running) {
11608 busiest_nr = nr_running;
11609 busiest = rq;
11610 }
11611 break;
11612
11613 case migrate_misfit:
11614 /*
11615 * For ASYM_CPUCAPACITY domains with misfit tasks we
11616 * simply seek the "biggest" misfit task.
11617 */
11618 if (rq->misfit_task_load > busiest_load) {
11619 busiest_load = rq->misfit_task_load;
11620 busiest = rq;
11621 }
11622
11623 break;
11624
11625 }
11626 }
11627
11628 return busiest;
11629 }
11630
11631 /*
11632 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11633 * so long as it is large enough.
11634 */
11635 #define MAX_PINNED_INTERVAL 512
11636
11637 static inline bool
asym_active_balance(struct lb_env * env)11638 asym_active_balance(struct lb_env *env)
11639 {
11640 /*
11641 * ASYM_PACKING needs to force migrate tasks from busy but lower
11642 * priority CPUs in order to pack all tasks in the highest priority
11643 * CPUs. When done between cores, do it only if the whole core if the
11644 * whole core is idle.
11645 *
11646 * If @env::src_cpu is an SMT core with busy siblings, let
11647 * the lower priority @env::dst_cpu help it. Do not follow
11648 * CPU priority.
11649 */
11650 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) &&
11651 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11652 !sched_use_asym_prio(env->sd, env->src_cpu));
11653 }
11654
11655 static inline bool
imbalanced_active_balance(struct lb_env * env)11656 imbalanced_active_balance(struct lb_env *env)
11657 {
11658 struct sched_domain *sd = env->sd;
11659
11660 /*
11661 * The imbalanced case includes the case of pinned tasks preventing a fair
11662 * distribution of the load on the system but also the even distribution of the
11663 * threads on a system with spare capacity
11664 */
11665 if ((env->migration_type == migrate_task) &&
11666 (sd->nr_balance_failed > sd->cache_nice_tries+2))
11667 return 1;
11668
11669 return 0;
11670 }
11671
need_active_balance(struct lb_env * env)11672 static int need_active_balance(struct lb_env *env)
11673 {
11674 struct sched_domain *sd = env->sd;
11675
11676 if (asym_active_balance(env))
11677 return 1;
11678
11679 if (imbalanced_active_balance(env))
11680 return 1;
11681
11682 /*
11683 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11684 * It's worth migrating the task if the src_cpu's capacity is reduced
11685 * because of other sched_class or IRQs if more capacity stays
11686 * available on dst_cpu.
11687 */
11688 if (env->idle &&
11689 (env->src_rq->cfs.h_nr_runnable == 1)) {
11690 if ((check_cpu_capacity(env->src_rq, sd)) &&
11691 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11692 return 1;
11693 }
11694
11695 if (env->migration_type == migrate_misfit)
11696 return 1;
11697
11698 return 0;
11699 }
11700
11701 static int active_load_balance_cpu_stop(void *data);
11702
should_we_balance(struct lb_env * env)11703 static int should_we_balance(struct lb_env *env)
11704 {
11705 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11706 struct sched_group *sg = env->sd->groups;
11707 int cpu, idle_smt = -1;
11708
11709 /*
11710 * Ensure the balancing environment is consistent; can happen
11711 * when the softirq triggers 'during' hotplug.
11712 */
11713 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11714 return 0;
11715
11716 /*
11717 * In the newly idle case, we will allow all the CPUs
11718 * to do the newly idle load balance.
11719 *
11720 * However, we bail out if we already have tasks or a wakeup pending,
11721 * to optimize wakeup latency.
11722 */
11723 if (env->idle == CPU_NEWLY_IDLE) {
11724 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11725 return 0;
11726 return 1;
11727 }
11728
11729 cpumask_copy(swb_cpus, group_balance_mask(sg));
11730 /* Try to find first idle CPU */
11731 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11732 if (!idle_cpu(cpu))
11733 continue;
11734
11735 /*
11736 * Don't balance to idle SMT in busy core right away when
11737 * balancing cores, but remember the first idle SMT CPU for
11738 * later consideration. Find CPU on an idle core first.
11739 */
11740 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11741 if (idle_smt == -1)
11742 idle_smt = cpu;
11743 /*
11744 * If the core is not idle, and first SMT sibling which is
11745 * idle has been found, then its not needed to check other
11746 * SMT siblings for idleness:
11747 */
11748 #ifdef CONFIG_SCHED_SMT
11749 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11750 #endif
11751 continue;
11752 }
11753
11754 /*
11755 * Are we the first idle core in a non-SMT domain or higher,
11756 * or the first idle CPU in a SMT domain?
11757 */
11758 return cpu == env->dst_cpu;
11759 }
11760
11761 /* Are we the first idle CPU with busy siblings? */
11762 if (idle_smt != -1)
11763 return idle_smt == env->dst_cpu;
11764
11765 /* Are we the first CPU of this group ? */
11766 return group_balance_cpu(sg) == env->dst_cpu;
11767 }
11768
update_lb_imbalance_stat(struct lb_env * env,struct sched_domain * sd,enum cpu_idle_type idle)11769 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd,
11770 enum cpu_idle_type idle)
11771 {
11772 if (!schedstat_enabled())
11773 return;
11774
11775 switch (env->migration_type) {
11776 case migrate_load:
11777 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance);
11778 break;
11779 case migrate_util:
11780 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance);
11781 break;
11782 case migrate_task:
11783 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance);
11784 break;
11785 case migrate_misfit:
11786 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance);
11787 break;
11788 }
11789 }
11790
11791 /*
11792 * This flag serializes load-balancing passes over large domains
11793 * (above the NODE topology level) - only one load-balancing instance
11794 * may run at a time, to reduce overhead on very large systems with
11795 * lots of CPUs and large NUMA distances.
11796 *
11797 * - Note that load-balancing passes triggered while another one
11798 * is executing are skipped and not re-tried.
11799 *
11800 * - Also note that this does not serialize rebalance_domains()
11801 * execution, as non-SD_SERIALIZE domains will still be
11802 * load-balanced in parallel.
11803 */
11804 static atomic_t sched_balance_running = ATOMIC_INIT(0);
11805
11806 /*
11807 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11808 * tasks if there is an imbalance.
11809 */
sched_balance_rq(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11810 static int sched_balance_rq(int this_cpu, struct rq *this_rq,
11811 struct sched_domain *sd, enum cpu_idle_type idle,
11812 int *continue_balancing)
11813 {
11814 int ld_moved, cur_ld_moved, active_balance = 0;
11815 struct sched_domain *sd_parent = sd->parent;
11816 struct sched_group *group;
11817 struct rq *busiest;
11818 struct rq_flags rf;
11819 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11820 struct lb_env env = {
11821 .sd = sd,
11822 .dst_cpu = this_cpu,
11823 .dst_rq = this_rq,
11824 .dst_grpmask = group_balance_mask(sd->groups),
11825 .idle = idle,
11826 .loop_break = SCHED_NR_MIGRATE_BREAK,
11827 .cpus = cpus,
11828 .fbq_type = all,
11829 .tasks = LIST_HEAD_INIT(env.tasks),
11830 };
11831 bool need_unlock = false;
11832
11833 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11834
11835 schedstat_inc(sd->lb_count[idle]);
11836
11837 redo:
11838 if (!should_we_balance(&env)) {
11839 *continue_balancing = 0;
11840 goto out_balanced;
11841 }
11842
11843 if (!need_unlock && (sd->flags & SD_SERIALIZE)) {
11844 int zero = 0;
11845 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1))
11846 goto out_balanced;
11847
11848 need_unlock = true;
11849 }
11850
11851 group = sched_balance_find_src_group(&env);
11852 if (!group) {
11853 schedstat_inc(sd->lb_nobusyg[idle]);
11854 goto out_balanced;
11855 }
11856
11857 busiest = sched_balance_find_src_rq(&env, group);
11858 if (!busiest) {
11859 schedstat_inc(sd->lb_nobusyq[idle]);
11860 goto out_balanced;
11861 }
11862
11863 WARN_ON_ONCE(busiest == env.dst_rq);
11864
11865 update_lb_imbalance_stat(&env, sd, idle);
11866
11867 env.src_cpu = busiest->cpu;
11868 env.src_rq = busiest;
11869
11870 ld_moved = 0;
11871 /* Clear this flag as soon as we find a pullable task */
11872 env.flags |= LBF_ALL_PINNED;
11873 if (busiest->nr_running > 1) {
11874 /*
11875 * Attempt to move tasks. If sched_balance_find_src_group has found
11876 * an imbalance but busiest->nr_running <= 1, the group is
11877 * still unbalanced. ld_moved simply stays zero, so it is
11878 * correctly treated as an imbalance.
11879 */
11880 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11881
11882 more_balance:
11883 rq_lock_irqsave(busiest, &rf);
11884 update_rq_clock(busiest);
11885
11886 /*
11887 * cur_ld_moved - load moved in current iteration
11888 * ld_moved - cumulative load moved across iterations
11889 */
11890 cur_ld_moved = detach_tasks(&env);
11891
11892 /*
11893 * We've detached some tasks from busiest_rq. Every
11894 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11895 * unlock busiest->lock, and we are able to be sure
11896 * that nobody can manipulate the tasks in parallel.
11897 * See task_rq_lock() family for the details.
11898 */
11899
11900 rq_unlock(busiest, &rf);
11901
11902 if (cur_ld_moved) {
11903 attach_tasks(&env);
11904 ld_moved += cur_ld_moved;
11905 }
11906
11907 local_irq_restore(rf.flags);
11908
11909 if (env.flags & LBF_NEED_BREAK) {
11910 env.flags &= ~LBF_NEED_BREAK;
11911 goto more_balance;
11912 }
11913
11914 /*
11915 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11916 * us and move them to an alternate dst_cpu in our sched_group
11917 * where they can run. The upper limit on how many times we
11918 * iterate on same src_cpu is dependent on number of CPUs in our
11919 * sched_group.
11920 *
11921 * This changes load balance semantics a bit on who can move
11922 * load to a given_cpu. In addition to the given_cpu itself
11923 * (or a ilb_cpu acting on its behalf where given_cpu is
11924 * nohz-idle), we now have balance_cpu in a position to move
11925 * load to given_cpu. In rare situations, this may cause
11926 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11927 * _independently_ and at _same_ time to move some load to
11928 * given_cpu) causing excess load to be moved to given_cpu.
11929 * This however should not happen so much in practice and
11930 * moreover subsequent load balance cycles should correct the
11931 * excess load moved.
11932 */
11933 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11934
11935 /* Prevent to re-select dst_cpu via env's CPUs */
11936 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11937
11938 env.dst_rq = cpu_rq(env.new_dst_cpu);
11939 env.dst_cpu = env.new_dst_cpu;
11940 env.flags &= ~LBF_DST_PINNED;
11941 env.loop = 0;
11942 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11943
11944 /*
11945 * Go back to "more_balance" rather than "redo" since we
11946 * need to continue with same src_cpu.
11947 */
11948 goto more_balance;
11949 }
11950
11951 /*
11952 * We failed to reach balance because of affinity.
11953 */
11954 if (sd_parent) {
11955 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11956
11957 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11958 *group_imbalance = 1;
11959 }
11960
11961 /* All tasks on this runqueue were pinned by CPU affinity */
11962 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11963 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11964 /*
11965 * Attempting to continue load balancing at the current
11966 * sched_domain level only makes sense if there are
11967 * active CPUs remaining as possible busiest CPUs to
11968 * pull load from which are not contained within the
11969 * destination group that is receiving any migrated
11970 * load.
11971 */
11972 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11973 env.loop = 0;
11974 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11975 goto redo;
11976 }
11977 goto out_all_pinned;
11978 }
11979 }
11980
11981 if (!ld_moved) {
11982 schedstat_inc(sd->lb_failed[idle]);
11983 /*
11984 * Increment the failure counter only on periodic balance.
11985 * We do not want newidle balance, which can be very
11986 * frequent, pollute the failure counter causing
11987 * excessive cache_hot migrations and active balances.
11988 *
11989 * Similarly for migration_misfit which is not related to
11990 * load/util migration, don't pollute nr_balance_failed.
11991 */
11992 if (idle != CPU_NEWLY_IDLE &&
11993 env.migration_type != migrate_misfit)
11994 sd->nr_balance_failed++;
11995
11996 if (need_active_balance(&env)) {
11997 unsigned long flags;
11998
11999 raw_spin_rq_lock_irqsave(busiest, flags);
12000
12001 /*
12002 * Don't kick the active_load_balance_cpu_stop,
12003 * if the curr task on busiest CPU can't be
12004 * moved to this_cpu:
12005 */
12006 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
12007 raw_spin_rq_unlock_irqrestore(busiest, flags);
12008 goto out_one_pinned;
12009 }
12010
12011 /* Record that we found at least one task that could run on this_cpu */
12012 env.flags &= ~LBF_ALL_PINNED;
12013
12014 /*
12015 * ->active_balance synchronizes accesses to
12016 * ->active_balance_work. Once set, it's cleared
12017 * only after active load balance is finished.
12018 */
12019 if (!busiest->active_balance) {
12020 busiest->active_balance = 1;
12021 busiest->push_cpu = this_cpu;
12022 active_balance = 1;
12023 }
12024
12025 preempt_disable();
12026 raw_spin_rq_unlock_irqrestore(busiest, flags);
12027 if (active_balance) {
12028 stop_one_cpu_nowait(cpu_of(busiest),
12029 active_load_balance_cpu_stop, busiest,
12030 &busiest->active_balance_work);
12031 }
12032 preempt_enable();
12033 }
12034 } else {
12035 sd->nr_balance_failed = 0;
12036 }
12037
12038 if (likely(!active_balance) || need_active_balance(&env)) {
12039 /* We were unbalanced, so reset the balancing interval */
12040 sd->balance_interval = sd->min_interval;
12041 }
12042
12043 goto out;
12044
12045 out_balanced:
12046 /*
12047 * We reach balance although we may have faced some affinity
12048 * constraints. Clear the imbalance flag only if other tasks got
12049 * a chance to move and fix the imbalance.
12050 */
12051 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
12052 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
12053
12054 if (*group_imbalance)
12055 *group_imbalance = 0;
12056 }
12057
12058 out_all_pinned:
12059 /*
12060 * We reach balance because all tasks are pinned at this level so
12061 * we can't migrate them. Let the imbalance flag set so parent level
12062 * can try to migrate them.
12063 */
12064 schedstat_inc(sd->lb_balanced[idle]);
12065
12066 sd->nr_balance_failed = 0;
12067
12068 out_one_pinned:
12069 ld_moved = 0;
12070
12071 /*
12072 * sched_balance_newidle() disregards balance intervals, so we could
12073 * repeatedly reach this code, which would lead to balance_interval
12074 * skyrocketing in a short amount of time. Skip the balance_interval
12075 * increase logic to avoid that.
12076 *
12077 * Similarly misfit migration which is not necessarily an indication of
12078 * the system being busy and requires lb to backoff to let it settle
12079 * down.
12080 */
12081 if (env.idle == CPU_NEWLY_IDLE ||
12082 env.migration_type == migrate_misfit)
12083 goto out;
12084
12085 /* tune up the balancing interval */
12086 if ((env.flags & LBF_ALL_PINNED &&
12087 sd->balance_interval < MAX_PINNED_INTERVAL) ||
12088 sd->balance_interval < sd->max_interval)
12089 sd->balance_interval *= 2;
12090 out:
12091 if (need_unlock)
12092 atomic_set_release(&sched_balance_running, 0);
12093
12094 return ld_moved;
12095 }
12096
12097 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)12098 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
12099 {
12100 unsigned long interval = sd->balance_interval;
12101
12102 if (cpu_busy)
12103 interval *= sd->busy_factor;
12104
12105 /* scale ms to jiffies */
12106 interval = msecs_to_jiffies(interval);
12107
12108 /*
12109 * Reduce likelihood of busy balancing at higher domains racing with
12110 * balancing at lower domains by preventing their balancing periods
12111 * from being multiples of each other.
12112 */
12113 if (cpu_busy)
12114 interval -= 1;
12115
12116 interval = clamp(interval, 1UL, max_load_balance_interval);
12117
12118 return interval;
12119 }
12120
12121 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)12122 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
12123 {
12124 unsigned long interval, next;
12125
12126 /* used by idle balance, so cpu_busy = 0 */
12127 interval = get_sd_balance_interval(sd, 0);
12128 next = sd->last_balance + interval;
12129
12130 if (time_after(*next_balance, next))
12131 *next_balance = next;
12132 }
12133
12134 /*
12135 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
12136 * running tasks off the busiest CPU onto idle CPUs. It requires at
12137 * least 1 task to be running on each physical CPU where possible, and
12138 * avoids physical / logical imbalances.
12139 */
active_load_balance_cpu_stop(void * data)12140 static int active_load_balance_cpu_stop(void *data)
12141 {
12142 struct rq *busiest_rq = data;
12143 int busiest_cpu = cpu_of(busiest_rq);
12144 int target_cpu = busiest_rq->push_cpu;
12145 struct rq *target_rq = cpu_rq(target_cpu);
12146 struct sched_domain *sd;
12147 struct task_struct *p = NULL;
12148 struct rq_flags rf;
12149
12150 rq_lock_irq(busiest_rq, &rf);
12151 /*
12152 * Between queueing the stop-work and running it is a hole in which
12153 * CPUs can become inactive. We should not move tasks from or to
12154 * inactive CPUs.
12155 */
12156 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
12157 goto out_unlock;
12158
12159 /* Make sure the requested CPU hasn't gone down in the meantime: */
12160 if (unlikely(busiest_cpu != smp_processor_id() ||
12161 !busiest_rq->active_balance))
12162 goto out_unlock;
12163
12164 /* Is there any task to move? */
12165 if (busiest_rq->nr_running <= 1)
12166 goto out_unlock;
12167
12168 /*
12169 * This condition is "impossible", if it occurs
12170 * we need to fix it. Originally reported by
12171 * Bjorn Helgaas on a 128-CPU setup.
12172 */
12173 WARN_ON_ONCE(busiest_rq == target_rq);
12174
12175 /* Search for an sd spanning us and the target CPU. */
12176 rcu_read_lock();
12177 for_each_domain(target_cpu, sd) {
12178 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
12179 break;
12180 }
12181
12182 if (likely(sd)) {
12183 struct lb_env env = {
12184 .sd = sd,
12185 .dst_cpu = target_cpu,
12186 .dst_rq = target_rq,
12187 .src_cpu = busiest_rq->cpu,
12188 .src_rq = busiest_rq,
12189 .idle = CPU_IDLE,
12190 .flags = LBF_ACTIVE_LB,
12191 };
12192
12193 schedstat_inc(sd->alb_count);
12194 update_rq_clock(busiest_rq);
12195
12196 p = detach_one_task(&env);
12197 if (p) {
12198 schedstat_inc(sd->alb_pushed);
12199 /* Active balancing done, reset the failure counter. */
12200 sd->nr_balance_failed = 0;
12201 } else {
12202 schedstat_inc(sd->alb_failed);
12203 }
12204 }
12205 rcu_read_unlock();
12206 out_unlock:
12207 busiest_rq->active_balance = 0;
12208 rq_unlock(busiest_rq, &rf);
12209
12210 if (p)
12211 attach_one_task(target_rq, p);
12212
12213 local_irq_enable();
12214
12215 return 0;
12216 }
12217
12218 /*
12219 * Scale the max sched_balance_rq interval with the number of CPUs in the system.
12220 * This trades load-balance latency on larger machines for less cross talk.
12221 */
update_max_interval(void)12222 void update_max_interval(void)
12223 {
12224 max_load_balance_interval = HZ*num_online_cpus()/10;
12225 }
12226
update_newidle_stats(struct sched_domain * sd,unsigned int success)12227 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success)
12228 {
12229 sd->newidle_call++;
12230 sd->newidle_success += success;
12231
12232 if (sd->newidle_call >= 1024) {
12233 sd->newidle_ratio = sd->newidle_success;
12234 sd->newidle_call /= 2;
12235 sd->newidle_success /= 2;
12236 }
12237 }
12238
12239 static inline bool
update_newidle_cost(struct sched_domain * sd,u64 cost,unsigned int success)12240 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success)
12241 {
12242 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ;
12243 unsigned long now = jiffies;
12244
12245 if (cost)
12246 update_newidle_stats(sd, success);
12247
12248 if (cost > sd->max_newidle_lb_cost) {
12249 /*
12250 * Track max cost of a domain to make sure to not delay the
12251 * next wakeup on the CPU.
12252 */
12253 sd->max_newidle_lb_cost = cost;
12254 sd->last_decay_max_lb_cost = now;
12255
12256 } else if (time_after(now, next_decay)) {
12257 /*
12258 * Decay the newidle max times by ~1% per second to ensure that
12259 * it is not outdated and the current max cost is actually
12260 * shorter.
12261 */
12262 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
12263 sd->last_decay_max_lb_cost = now;
12264 return true;
12265 }
12266
12267 return false;
12268 }
12269
12270 /*
12271 * It checks each scheduling domain to see if it is due to be balanced,
12272 * and initiates a balancing operation if so.
12273 *
12274 * Balancing parameters are set up in init_sched_domains.
12275 */
sched_balance_domains(struct rq * rq,enum cpu_idle_type idle)12276 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle)
12277 {
12278 int continue_balancing = 1;
12279 int cpu = rq->cpu;
12280 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
12281 unsigned long interval;
12282 struct sched_domain *sd;
12283 /* Earliest time when we have to do rebalance again */
12284 unsigned long next_balance = jiffies + 60*HZ;
12285 int update_next_balance = 0;
12286 int need_decay = 0;
12287 u64 max_cost = 0;
12288
12289 rcu_read_lock();
12290 for_each_domain(cpu, sd) {
12291 /*
12292 * Decay the newidle max times here because this is a regular
12293 * visit to all the domains.
12294 */
12295 need_decay = update_newidle_cost(sd, 0, 0);
12296 max_cost += sd->max_newidle_lb_cost;
12297
12298 /*
12299 * Stop the load balance at this level. There is another
12300 * CPU in our sched group which is doing load balancing more
12301 * actively.
12302 */
12303 if (!continue_balancing) {
12304 if (need_decay)
12305 continue;
12306 break;
12307 }
12308
12309 interval = get_sd_balance_interval(sd, busy);
12310 if (time_after_eq(jiffies, sd->last_balance + interval)) {
12311 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) {
12312 /*
12313 * The LBF_DST_PINNED logic could have changed
12314 * env->dst_cpu, so we can't know our idle
12315 * state even if we migrated tasks. Update it.
12316 */
12317 idle = idle_cpu(cpu);
12318 busy = !idle && !sched_idle_cpu(cpu);
12319 }
12320 sd->last_balance = jiffies;
12321 interval = get_sd_balance_interval(sd, busy);
12322 }
12323 if (time_after(next_balance, sd->last_balance + interval)) {
12324 next_balance = sd->last_balance + interval;
12325 update_next_balance = 1;
12326 }
12327 }
12328 if (need_decay) {
12329 /*
12330 * Ensure the rq-wide value also decays but keep it at a
12331 * reasonable floor to avoid funnies with rq->avg_idle.
12332 */
12333 rq->max_idle_balance_cost =
12334 max((u64)sysctl_sched_migration_cost, max_cost);
12335 }
12336 rcu_read_unlock();
12337
12338 /*
12339 * next_balance will be updated only when there is a need.
12340 * When the cpu is attached to null domain for ex, it will not be
12341 * updated.
12342 */
12343 if (likely(update_next_balance))
12344 rq->next_balance = next_balance;
12345
12346 }
12347
on_null_domain(struct rq * rq)12348 static inline int on_null_domain(struct rq *rq)
12349 {
12350 return unlikely(!rcu_dereference_sched(rq->sd));
12351 }
12352
12353 #ifdef CONFIG_NO_HZ_COMMON
12354 /*
12355 * NOHZ idle load balancing (ILB) details:
12356 *
12357 * - When one of the busy CPUs notices that there may be an idle rebalancing
12358 * needed, they will kick the idle load balancer, which then does idle
12359 * load balancing for all the idle CPUs.
12360 */
find_new_ilb(void)12361 static inline int find_new_ilb(void)
12362 {
12363 const struct cpumask *hk_mask;
12364 int ilb_cpu;
12365
12366 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE);
12367
12368 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) {
12369
12370 if (ilb_cpu == smp_processor_id())
12371 continue;
12372
12373 if (idle_cpu(ilb_cpu))
12374 return ilb_cpu;
12375 }
12376
12377 return -1;
12378 }
12379
12380 /*
12381 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU
12382 * SMP function call (IPI).
12383 *
12384 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set
12385 * (if there is one).
12386 */
kick_ilb(unsigned int flags)12387 static void kick_ilb(unsigned int flags)
12388 {
12389 int ilb_cpu;
12390
12391 /*
12392 * Increase nohz.next_balance only when if full ilb is triggered but
12393 * not if we only update stats.
12394 */
12395 if (flags & NOHZ_BALANCE_KICK)
12396 nohz.next_balance = jiffies+1;
12397
12398 ilb_cpu = find_new_ilb();
12399 if (ilb_cpu < 0)
12400 return;
12401
12402 /*
12403 * Don't bother if no new NOHZ balance work items for ilb_cpu,
12404 * i.e. all bits in flags are already set in ilb_cpu.
12405 */
12406 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags)
12407 return;
12408
12409 /*
12410 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
12411 * the first flag owns it; cleared by nohz_csd_func().
12412 */
12413 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
12414 if (flags & NOHZ_KICK_MASK)
12415 return;
12416
12417 /*
12418 * This way we generate an IPI on the target CPU which
12419 * is idle, and the softirq performing NOHZ idle load balancing
12420 * will be run before returning from the IPI.
12421 */
12422 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
12423 }
12424
12425 /*
12426 * Current decision point for kicking the idle load balancer in the presence
12427 * of idle CPUs in the system.
12428 */
nohz_balancer_kick(struct rq * rq)12429 static void nohz_balancer_kick(struct rq *rq)
12430 {
12431 unsigned long now = jiffies;
12432 struct sched_domain_shared *sds;
12433 struct sched_domain *sd;
12434 int nr_busy, i, cpu = rq->cpu;
12435 unsigned int flags = 0;
12436
12437 if (unlikely(rq->idle_balance))
12438 return;
12439
12440 /*
12441 * We may be recently in ticked or tickless idle mode. At the first
12442 * busy tick after returning from idle, we will update the busy stats.
12443 */
12444 nohz_balance_exit_idle(rq);
12445
12446 /*
12447 * None are in tickless mode and hence no need for NOHZ idle load
12448 * balancing:
12449 */
12450 if (likely(!atomic_read(&nohz.nr_cpus)))
12451 return;
12452
12453 if (READ_ONCE(nohz.has_blocked) &&
12454 time_after(now, READ_ONCE(nohz.next_blocked)))
12455 flags = NOHZ_STATS_KICK;
12456
12457 if (time_before(now, nohz.next_balance))
12458 goto out;
12459
12460 if (rq->nr_running >= 2) {
12461 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12462 goto out;
12463 }
12464
12465 rcu_read_lock();
12466
12467 sd = rcu_dereference(rq->sd);
12468 if (sd) {
12469 /*
12470 * If there's a runnable CFS task and the current CPU has reduced
12471 * capacity, kick the ILB to see if there's a better CPU to run on:
12472 */
12473 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) {
12474 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12475 goto unlock;
12476 }
12477 }
12478
12479 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
12480 if (sd) {
12481 /*
12482 * When ASYM_PACKING; see if there's a more preferred CPU
12483 * currently idle; in which case, kick the ILB to move tasks
12484 * around.
12485 *
12486 * When balancing between cores, all the SMT siblings of the
12487 * preferred CPU must be idle.
12488 */
12489 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
12490 if (sched_asym(sd, i, cpu)) {
12491 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12492 goto unlock;
12493 }
12494 }
12495 }
12496
12497 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
12498 if (sd) {
12499 /*
12500 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
12501 * to run the misfit task on.
12502 */
12503 if (check_misfit_status(rq)) {
12504 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12505 goto unlock;
12506 }
12507
12508 /*
12509 * For asymmetric systems, we do not want to nicely balance
12510 * cache use, instead we want to embrace asymmetry and only
12511 * ensure tasks have enough CPU capacity.
12512 *
12513 * Skip the LLC logic because it's not relevant in that case.
12514 */
12515 goto unlock;
12516 }
12517
12518 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
12519 if (sds) {
12520 /*
12521 * If there is an imbalance between LLC domains (IOW we could
12522 * increase the overall cache utilization), we need a less-loaded LLC
12523 * domain to pull some load from. Likewise, we may need to spread
12524 * load within the current LLC domain (e.g. packed SMT cores but
12525 * other CPUs are idle). We can't really know from here how busy
12526 * the others are - so just get a NOHZ balance going if it looks
12527 * like this LLC domain has tasks we could move.
12528 */
12529 nr_busy = atomic_read(&sds->nr_busy_cpus);
12530 if (nr_busy > 1) {
12531 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12532 goto unlock;
12533 }
12534 }
12535 unlock:
12536 rcu_read_unlock();
12537 out:
12538 if (READ_ONCE(nohz.needs_update))
12539 flags |= NOHZ_NEXT_KICK;
12540
12541 if (flags)
12542 kick_ilb(flags);
12543 }
12544
set_cpu_sd_state_busy(int cpu)12545 static void set_cpu_sd_state_busy(int cpu)
12546 {
12547 struct sched_domain *sd;
12548
12549 rcu_read_lock();
12550 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12551
12552 if (!sd || !sd->nohz_idle)
12553 goto unlock;
12554 sd->nohz_idle = 0;
12555
12556 atomic_inc(&sd->shared->nr_busy_cpus);
12557 unlock:
12558 rcu_read_unlock();
12559 }
12560
nohz_balance_exit_idle(struct rq * rq)12561 void nohz_balance_exit_idle(struct rq *rq)
12562 {
12563 WARN_ON_ONCE(rq != this_rq());
12564
12565 if (likely(!rq->nohz_tick_stopped))
12566 return;
12567
12568 rq->nohz_tick_stopped = 0;
12569 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12570 atomic_dec(&nohz.nr_cpus);
12571
12572 set_cpu_sd_state_busy(rq->cpu);
12573 }
12574
set_cpu_sd_state_idle(int cpu)12575 static void set_cpu_sd_state_idle(int cpu)
12576 {
12577 struct sched_domain *sd;
12578
12579 rcu_read_lock();
12580 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12581
12582 if (!sd || sd->nohz_idle)
12583 goto unlock;
12584 sd->nohz_idle = 1;
12585
12586 atomic_dec(&sd->shared->nr_busy_cpus);
12587 unlock:
12588 rcu_read_unlock();
12589 }
12590
12591 /*
12592 * This routine will record that the CPU is going idle with tick stopped.
12593 * This info will be used in performing idle load balancing in the future.
12594 */
nohz_balance_enter_idle(int cpu)12595 void nohz_balance_enter_idle(int cpu)
12596 {
12597 struct rq *rq = cpu_rq(cpu);
12598
12599 WARN_ON_ONCE(cpu != smp_processor_id());
12600
12601 /* If this CPU is going down, then nothing needs to be done: */
12602 if (!cpu_active(cpu))
12603 return;
12604
12605 /*
12606 * Can be set safely without rq->lock held
12607 * If a clear happens, it will have evaluated last additions because
12608 * rq->lock is held during the check and the clear
12609 */
12610 rq->has_blocked_load = 1;
12611
12612 /*
12613 * The tick is still stopped but load could have been added in the
12614 * meantime. We set the nohz.has_blocked flag to trig a check of the
12615 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12616 * of nohz.has_blocked can only happen after checking the new load
12617 */
12618 if (rq->nohz_tick_stopped)
12619 goto out;
12620
12621 /* If we're a completely isolated CPU, we don't play: */
12622 if (on_null_domain(rq))
12623 return;
12624
12625 rq->nohz_tick_stopped = 1;
12626
12627 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12628 atomic_inc(&nohz.nr_cpus);
12629
12630 /*
12631 * Ensures that if nohz_idle_balance() fails to observe our
12632 * @idle_cpus_mask store, it must observe the @has_blocked
12633 * and @needs_update stores.
12634 */
12635 smp_mb__after_atomic();
12636
12637 set_cpu_sd_state_idle(cpu);
12638
12639 WRITE_ONCE(nohz.needs_update, 1);
12640 out:
12641 /*
12642 * Each time a cpu enter idle, we assume that it has blocked load and
12643 * enable the periodic update of the load of idle CPUs
12644 */
12645 WRITE_ONCE(nohz.has_blocked, 1);
12646 }
12647
update_nohz_stats(struct rq * rq)12648 static bool update_nohz_stats(struct rq *rq)
12649 {
12650 unsigned int cpu = rq->cpu;
12651
12652 if (!rq->has_blocked_load)
12653 return false;
12654
12655 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12656 return false;
12657
12658 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12659 return true;
12660
12661 sched_balance_update_blocked_averages(cpu);
12662
12663 return rq->has_blocked_load;
12664 }
12665
12666 /*
12667 * Internal function that runs load balance for all idle CPUs. The load balance
12668 * can be a simple update of blocked load or a complete load balance with
12669 * tasks movement depending of flags.
12670 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12671 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12672 {
12673 /* Earliest time when we have to do rebalance again */
12674 unsigned long now = jiffies;
12675 unsigned long next_balance = now + 60*HZ;
12676 bool has_blocked_load = false;
12677 int update_next_balance = 0;
12678 int this_cpu = this_rq->cpu;
12679 int balance_cpu;
12680 struct rq *rq;
12681
12682 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12683
12684 /*
12685 * We assume there will be no idle load after this update and clear
12686 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12687 * set the has_blocked flag and trigger another update of idle load.
12688 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12689 * setting the flag, we are sure to not clear the state and not
12690 * check the load of an idle cpu.
12691 *
12692 * Same applies to idle_cpus_mask vs needs_update.
12693 */
12694 if (flags & NOHZ_STATS_KICK)
12695 WRITE_ONCE(nohz.has_blocked, 0);
12696 if (flags & NOHZ_NEXT_KICK)
12697 WRITE_ONCE(nohz.needs_update, 0);
12698
12699 /*
12700 * Ensures that if we miss the CPU, we must see the has_blocked
12701 * store from nohz_balance_enter_idle().
12702 */
12703 smp_mb();
12704
12705 /*
12706 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12707 * chance for other idle cpu to pull load.
12708 */
12709 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
12710 if (!idle_cpu(balance_cpu))
12711 continue;
12712
12713 /*
12714 * If this CPU gets work to do, stop the load balancing
12715 * work being done for other CPUs. Next load
12716 * balancing owner will pick it up.
12717 */
12718 if (!idle_cpu(this_cpu) && need_resched()) {
12719 if (flags & NOHZ_STATS_KICK)
12720 has_blocked_load = true;
12721 if (flags & NOHZ_NEXT_KICK)
12722 WRITE_ONCE(nohz.needs_update, 1);
12723 goto abort;
12724 }
12725
12726 rq = cpu_rq(balance_cpu);
12727
12728 if (flags & NOHZ_STATS_KICK)
12729 has_blocked_load |= update_nohz_stats(rq);
12730
12731 /*
12732 * If time for next balance is due,
12733 * do the balance.
12734 */
12735 if (time_after_eq(jiffies, rq->next_balance)) {
12736 struct rq_flags rf;
12737
12738 rq_lock_irqsave(rq, &rf);
12739 update_rq_clock(rq);
12740 rq_unlock_irqrestore(rq, &rf);
12741
12742 if (flags & NOHZ_BALANCE_KICK)
12743 sched_balance_domains(rq, CPU_IDLE);
12744 }
12745
12746 if (time_after(next_balance, rq->next_balance)) {
12747 next_balance = rq->next_balance;
12748 update_next_balance = 1;
12749 }
12750 }
12751
12752 /*
12753 * next_balance will be updated only when there is a need.
12754 * When the CPU is attached to null domain for ex, it will not be
12755 * updated.
12756 */
12757 if (likely(update_next_balance))
12758 nohz.next_balance = next_balance;
12759
12760 if (flags & NOHZ_STATS_KICK)
12761 WRITE_ONCE(nohz.next_blocked,
12762 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12763
12764 abort:
12765 /* There is still blocked load, enable periodic update */
12766 if (has_blocked_load)
12767 WRITE_ONCE(nohz.has_blocked, 1);
12768 }
12769
12770 /*
12771 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12772 * rebalancing for all the CPUs for whom scheduler ticks are stopped.
12773 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12774 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12775 {
12776 unsigned int flags = this_rq->nohz_idle_balance;
12777
12778 if (!flags)
12779 return false;
12780
12781 this_rq->nohz_idle_balance = 0;
12782
12783 if (idle != CPU_IDLE)
12784 return false;
12785
12786 _nohz_idle_balance(this_rq, flags);
12787
12788 return true;
12789 }
12790
12791 /*
12792 * Check if we need to directly run the ILB for updating blocked load before
12793 * entering idle state. Here we run ILB directly without issuing IPIs.
12794 *
12795 * Note that when this function is called, the tick may not yet be stopped on
12796 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and
12797 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates
12798 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle
12799 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is
12800 * called from this function on (this) CPU that's not yet in the mask. That's
12801 * OK because the goal of nohz_run_idle_balance() is to run ILB only for
12802 * updating the blocked load of already idle CPUs without waking up one of
12803 * those idle CPUs and outside the preempt disable / IRQ off phase of the local
12804 * cpu about to enter idle, because it can take a long time.
12805 */
nohz_run_idle_balance(int cpu)12806 void nohz_run_idle_balance(int cpu)
12807 {
12808 unsigned int flags;
12809
12810 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12811
12812 /*
12813 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12814 * (i.e. NOHZ_STATS_KICK set) and will do the same.
12815 */
12816 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12817 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12818 }
12819
nohz_newidle_balance(struct rq * this_rq)12820 static void nohz_newidle_balance(struct rq *this_rq)
12821 {
12822 int this_cpu = this_rq->cpu;
12823
12824 /* Will wake up very soon. No time for doing anything else*/
12825 if (this_rq->avg_idle < sysctl_sched_migration_cost)
12826 return;
12827
12828 /* Don't need to update blocked load of idle CPUs*/
12829 if (!READ_ONCE(nohz.has_blocked) ||
12830 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12831 return;
12832
12833 /*
12834 * Set the need to trigger ILB in order to update blocked load
12835 * before entering idle state.
12836 */
12837 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12838 }
12839
12840 #else /* !CONFIG_NO_HZ_COMMON: */
nohz_balancer_kick(struct rq * rq)12841 static inline void nohz_balancer_kick(struct rq *rq) { }
12842
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12843 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12844 {
12845 return false;
12846 }
12847
nohz_newidle_balance(struct rq * this_rq)12848 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12849 #endif /* !CONFIG_NO_HZ_COMMON */
12850
12851 /*
12852 * sched_balance_newidle is called by schedule() if this_cpu is about to become
12853 * idle. Attempts to pull tasks from other CPUs.
12854 *
12855 * Returns:
12856 * < 0 - we released the lock and there are !fair tasks present
12857 * 0 - failed, no new tasks
12858 * > 0 - success, new (fair) tasks present
12859 */
sched_balance_newidle(struct rq * this_rq,struct rq_flags * rf)12860 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf)
12861 {
12862 unsigned long next_balance = jiffies + HZ;
12863 int this_cpu = this_rq->cpu;
12864 int continue_balancing = 1;
12865 u64 t0, t1, curr_cost = 0;
12866 struct sched_domain *sd;
12867 int pulled_task = 0;
12868
12869 update_misfit_status(NULL, this_rq);
12870
12871 /*
12872 * There is a task waiting to run. No need to search for one.
12873 * Return 0; the task will be enqueued when switching to idle.
12874 */
12875 if (this_rq->ttwu_pending)
12876 return 0;
12877
12878 /*
12879 * We must set idle_stamp _before_ calling sched_balance_rq()
12880 * for CPU_NEWLY_IDLE, such that we measure the this duration
12881 * as idle time.
12882 */
12883 this_rq->idle_stamp = rq_clock(this_rq);
12884
12885 /*
12886 * Do not pull tasks towards !active CPUs...
12887 */
12888 if (!cpu_active(this_cpu))
12889 return 0;
12890
12891 /*
12892 * This is OK, because current is on_cpu, which avoids it being picked
12893 * for load-balance and preemption/IRQs are still disabled avoiding
12894 * further scheduler activity on it and we're being very careful to
12895 * re-start the picking loop.
12896 */
12897 rq_unpin_lock(this_rq, rf);
12898
12899 rcu_read_lock();
12900 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12901 if (!sd) {
12902 rcu_read_unlock();
12903 goto out;
12904 }
12905
12906 if (!get_rd_overloaded(this_rq->rd) ||
12907 this_rq->avg_idle < sd->max_newidle_lb_cost) {
12908
12909 update_next_balance(sd, &next_balance);
12910 rcu_read_unlock();
12911 goto out;
12912 }
12913 rcu_read_unlock();
12914
12915 rq_modified_clear(this_rq);
12916 raw_spin_rq_unlock(this_rq);
12917
12918 t0 = sched_clock_cpu(this_cpu);
12919 sched_balance_update_blocked_averages(this_cpu);
12920
12921 rcu_read_lock();
12922 for_each_domain(this_cpu, sd) {
12923 u64 domain_cost;
12924
12925 update_next_balance(sd, &next_balance);
12926
12927 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12928 break;
12929
12930 if (sd->flags & SD_BALANCE_NEWIDLE) {
12931 unsigned int weight = 1;
12932
12933 if (sched_feat(NI_RANDOM)) {
12934 /*
12935 * Throw a 1k sided dice; and only run
12936 * newidle_balance according to the success
12937 * rate.
12938 */
12939 u32 d1k = sched_rng() % 1024;
12940 weight = 1 + sd->newidle_ratio;
12941 if (d1k > weight) {
12942 update_newidle_stats(sd, 0);
12943 continue;
12944 }
12945 weight = (1024 + weight/2) / weight;
12946 }
12947
12948 pulled_task = sched_balance_rq(this_cpu, this_rq,
12949 sd, CPU_NEWLY_IDLE,
12950 &continue_balancing);
12951
12952 t1 = sched_clock_cpu(this_cpu);
12953 domain_cost = t1 - t0;
12954 curr_cost += domain_cost;
12955 t0 = t1;
12956
12957 /*
12958 * Track max cost of a domain to make sure to not delay the
12959 * next wakeup on the CPU.
12960 */
12961 update_newidle_cost(sd, domain_cost, weight * !!pulled_task);
12962 }
12963
12964 /*
12965 * Stop searching for tasks to pull if there are
12966 * now runnable tasks on this rq.
12967 */
12968 if (pulled_task || !continue_balancing)
12969 break;
12970 }
12971 rcu_read_unlock();
12972
12973 raw_spin_rq_lock(this_rq);
12974
12975 if (curr_cost > this_rq->max_idle_balance_cost)
12976 this_rq->max_idle_balance_cost = curr_cost;
12977
12978 /*
12979 * While browsing the domains, we released the rq lock, a task could
12980 * have been enqueued in the meantime. Since we're not going idle,
12981 * pretend we pulled a task.
12982 */
12983 if (this_rq->cfs.h_nr_queued && !pulled_task)
12984 pulled_task = 1;
12985
12986 /* If a higher prio class was modified, restart the pick */
12987 if (rq_modified_above(this_rq, &fair_sched_class))
12988 pulled_task = -1;
12989
12990 out:
12991 /* Move the next balance forward */
12992 if (time_after(this_rq->next_balance, next_balance))
12993 this_rq->next_balance = next_balance;
12994
12995 if (pulled_task)
12996 this_rq->idle_stamp = 0;
12997 else
12998 nohz_newidle_balance(this_rq);
12999
13000 rq_repin_lock(this_rq, rf);
13001
13002 return pulled_task;
13003 }
13004
13005 /*
13006 * This softirq handler is triggered via SCHED_SOFTIRQ from two places:
13007 *
13008 * - directly from the local sched_tick() for periodic load balancing
13009 *
13010 * - indirectly from a remote sched_tick() for NOHZ idle balancing
13011 * through the SMP cross-call nohz_csd_func()
13012 */
sched_balance_softirq(void)13013 static __latent_entropy void sched_balance_softirq(void)
13014 {
13015 struct rq *this_rq = this_rq();
13016 enum cpu_idle_type idle = this_rq->idle_balance;
13017 /*
13018 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the
13019 * balancing on behalf of the other idle CPUs whose ticks are
13020 * stopped. Do nohz_idle_balance *before* sched_balance_domains to
13021 * give the idle CPUs a chance to load balance. Else we may
13022 * load balance only within the local sched_domain hierarchy
13023 * and abort nohz_idle_balance altogether if we pull some load.
13024 */
13025 if (nohz_idle_balance(this_rq, idle))
13026 return;
13027
13028 /* normal load balance */
13029 sched_balance_update_blocked_averages(this_rq->cpu);
13030 sched_balance_domains(this_rq, idle);
13031 }
13032
13033 /*
13034 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
13035 */
sched_balance_trigger(struct rq * rq)13036 void sched_balance_trigger(struct rq *rq)
13037 {
13038 /*
13039 * Don't need to rebalance while attached to NULL domain or
13040 * runqueue CPU is not active
13041 */
13042 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
13043 return;
13044
13045 if (time_after_eq(jiffies, rq->next_balance))
13046 raise_softirq(SCHED_SOFTIRQ);
13047
13048 nohz_balancer_kick(rq);
13049 }
13050
rq_online_fair(struct rq * rq)13051 static void rq_online_fair(struct rq *rq)
13052 {
13053 update_sysctl();
13054
13055 update_runtime_enabled(rq);
13056 }
13057
rq_offline_fair(struct rq * rq)13058 static void rq_offline_fair(struct rq *rq)
13059 {
13060 update_sysctl();
13061
13062 /* Ensure any throttled groups are reachable by pick_next_task */
13063 unthrottle_offline_cfs_rqs(rq);
13064
13065 /* Ensure that we remove rq contribution to group share: */
13066 clear_tg_offline_cfs_rqs(rq);
13067 }
13068
13069 #ifdef CONFIG_SCHED_CORE
13070 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)13071 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
13072 {
13073 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
13074 u64 slice = se->slice;
13075
13076 return (rtime * min_nr_tasks > slice);
13077 }
13078
13079 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
task_tick_core(struct rq * rq,struct task_struct * curr)13080 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
13081 {
13082 if (!sched_core_enabled(rq))
13083 return;
13084
13085 /*
13086 * If runqueue has only one task which used up its slice and
13087 * if the sibling is forced idle, then trigger schedule to
13088 * give forced idle task a chance.
13089 *
13090 * sched_slice() considers only this active rq and it gets the
13091 * whole slice. But during force idle, we have siblings acting
13092 * like a single runqueue and hence we need to consider runnable
13093 * tasks on this CPU and the forced idle CPU. Ideally, we should
13094 * go through the forced idle rq, but that would be a perf hit.
13095 * We can assume that the forced idle CPU has at least
13096 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
13097 * if we need to give up the CPU.
13098 */
13099 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 &&
13100 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
13101 resched_curr(rq);
13102 }
13103
13104 /*
13105 * Consider any infeasible weight scenario. Take for instance two tasks,
13106 * each bound to their respective sibling, one with weight 1 and one with
13107 * weight 2. Then the lower weight task will run ahead of the higher weight
13108 * task without bound.
13109 *
13110 * This utterly destroys the concept of a shared time base.
13111 *
13112 * Remember; all this is about a proportionally fair scheduling, where each
13113 * tasks receives:
13114 *
13115 * w_i
13116 * dt_i = ---------- dt (1)
13117 * \Sum_j w_j
13118 *
13119 * which we do by tracking a virtual time, s_i:
13120 *
13121 * 1
13122 * s_i = --- d[t]_i (2)
13123 * w_i
13124 *
13125 * Where d[t] is a delta of discrete time, while dt is an infinitesimal.
13126 * The immediate corollary is that the ideal schedule S, where (2) to use
13127 * an infinitesimal delta, is:
13128 *
13129 * 1
13130 * S = ---------- dt (3)
13131 * \Sum_i w_i
13132 *
13133 * From which we can define the lag, or deviation from the ideal, as:
13134 *
13135 * lag(i) = S - s_i (4)
13136 *
13137 * And since the one and only purpose is to approximate S, we get that:
13138 *
13139 * \Sum_i w_i lag(i) := 0 (5)
13140 *
13141 * If this were not so, we no longer converge to S, and we can no longer
13142 * claim our scheduler has any of the properties we derive from S. This is
13143 * exactly what you did above, you broke it!
13144 *
13145 *
13146 * Let's continue for a while though; to see if there is anything useful to
13147 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i:
13148 *
13149 * \Sum_i w_i s_i
13150 * S = -------------- (6)
13151 * \Sum_i w_i
13152 *
13153 * Which gives us a way to compute S, given our s_i. Now, if you've read
13154 * our code, you know that we do not in fact do this, the reason for this
13155 * is two-fold. Firstly, computing S in that way requires a 64bit division
13156 * for every time we'd use it (see 12), and secondly, this only describes
13157 * the steady-state, it doesn't handle dynamics.
13158 *
13159 * Anyway, in (6): s_i -> x + (s_i - x), to get:
13160 *
13161 * \Sum_i w_i (s_i - x)
13162 * S - x = -------------------- (7)
13163 * \Sum_i w_i
13164 *
13165 * Which shows that S and s_i transform alike (which makes perfect sense
13166 * given that S is basically the (weighted) average of s_i).
13167 *
13168 * So the thing to remember is that the above is strictly UP. It is
13169 * possible to generalize to multiple runqueues -- however it gets really
13170 * yuck when you have to add affinity support, as illustrated by our very
13171 * first counter-example.
13172 *
13173 * Luckily I think we can avoid needing a full multi-queue variant for
13174 * core-scheduling (or load-balancing). The crucial observation is that we
13175 * only actually need this comparison in the presence of forced-idle; only
13176 * then do we need to tell if the stalled rq has higher priority over the
13177 * other.
13178 *
13179 * [XXX assumes SMT2; better consider the more general case, I suspect
13180 * it'll work out because our comparison is always between 2 rqs and the
13181 * answer is only interesting if one of them is forced-idle]
13182 *
13183 * And (under assumption of SMT2) when there is forced-idle, there is only
13184 * a single queue, so everything works like normal.
13185 *
13186 * Let, for our runqueue 'k':
13187 *
13188 * T_k = \Sum_i w_i s_i
13189 * W_k = \Sum_i w_i ; for all i of k (8)
13190 *
13191 * Then we can write (6) like:
13192 *
13193 * T_k
13194 * S_k = --- (9)
13195 * W_k
13196 *
13197 * From which immediately follows that:
13198 *
13199 * T_k + T_l
13200 * S_k+l = --------- (10)
13201 * W_k + W_l
13202 *
13203 * On which we can define a combined lag:
13204 *
13205 * lag_k+l(i) := S_k+l - s_i (11)
13206 *
13207 * And that gives us the tools to compare tasks across a combined runqueue.
13208 *
13209 *
13210 * Combined this gives the following:
13211 *
13212 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s)
13213 * using (7); this only requires storing single 'time'-stamps.
13214 *
13215 * b) when comparing tasks between 2 runqueues of which one is forced-idle,
13216 * compare the combined lag, per (11).
13217 *
13218 * Now, of course cgroups (I so hate them) make this more interesting in
13219 * that a) seems to suggest we need to iterate all cgroup on a CPU at such
13220 * boundaries, but I think we can avoid that. The force-idle is for the
13221 * whole CPU, all it's rqs. So we can mark it in the root and lazily
13222 * propagate downward on demand.
13223 */
13224
13225 /*
13226 * So this sync is basically a relative reset of S to 0.
13227 *
13228 * So with 2 queues, when one goes idle, we drop them both to 0 and one
13229 * then increases due to not being idle, and the idle one builds up lag to
13230 * get re-elected. So far so simple, right?
13231 *
13232 * When there's 3, we can have the situation where 2 run and one is idle,
13233 * we sync to 0 and let the idle one build up lag to get re-election. Now
13234 * suppose another one also drops idle. At this point dropping all to 0
13235 * again would destroy the built-up lag from the queue that was already
13236 * idle, not good.
13237 *
13238 * So instead of syncing everything, we can:
13239 *
13240 * less := !((s64)(s_a - s_b) <= 0)
13241 *
13242 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b
13243 * == v_a - (v_b - S_a + S_b)
13244 *
13245 * IOW, we can recast the (lag) comparison to a one-sided difference.
13246 * So if then, instead of syncing the whole queue, sync the idle queue
13247 * against the active queue with S_a + S_b at the point where we sync.
13248 *
13249 * (XXX consider the implication of living in a cyclic group: N / 2^n N)
13250 *
13251 * This gives us means of syncing single queues against the active queue,
13252 * and for already idle queues to preserve their build-up lag.
13253 *
13254 * Of course, then we get the situation where there's 2 active and one
13255 * going idle, who do we pick to sync against? Theory would have us sync
13256 * against the combined S, but as we've already demonstrated, there is no
13257 * such thing in infeasible weight scenarios.
13258 *
13259 * One thing I've considered; and this is where that core_active rudiment
13260 * came from, is having active queues sync up between themselves after
13261 * every tick. This limits the observed divergence due to the work
13262 * conservancy.
13263 *
13264 * On top of that, we can improve upon things by employing (10) here.
13265 */
13266
13267 /*
13268 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed.
13269 */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)13270 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
13271 bool forceidle)
13272 {
13273 for_each_sched_entity(se) {
13274 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13275
13276 if (forceidle) {
13277 if (cfs_rq->forceidle_seq == fi_seq)
13278 break;
13279 cfs_rq->forceidle_seq = fi_seq;
13280 }
13281
13282 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime;
13283 }
13284 }
13285
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)13286 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
13287 {
13288 struct sched_entity *se = &p->se;
13289
13290 if (p->sched_class != &fair_sched_class)
13291 return;
13292
13293 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
13294 }
13295
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)13296 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
13297 bool in_fi)
13298 {
13299 struct rq *rq = task_rq(a);
13300 const struct sched_entity *sea = &a->se;
13301 const struct sched_entity *seb = &b->se;
13302 struct cfs_rq *cfs_rqa;
13303 struct cfs_rq *cfs_rqb;
13304 s64 delta;
13305
13306 WARN_ON_ONCE(task_rq(b)->core != rq->core);
13307
13308 #ifdef CONFIG_FAIR_GROUP_SCHED
13309 /*
13310 * Find an se in the hierarchy for tasks a and b, such that the se's
13311 * are immediate siblings.
13312 */
13313 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
13314 int sea_depth = sea->depth;
13315 int seb_depth = seb->depth;
13316
13317 if (sea_depth >= seb_depth)
13318 sea = parent_entity(sea);
13319 if (sea_depth <= seb_depth)
13320 seb = parent_entity(seb);
13321 }
13322
13323 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
13324 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
13325
13326 cfs_rqa = sea->cfs_rq;
13327 cfs_rqb = seb->cfs_rq;
13328 #else /* !CONFIG_FAIR_GROUP_SCHED: */
13329 cfs_rqa = &task_rq(a)->cfs;
13330 cfs_rqb = &task_rq(b)->cfs;
13331 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13332
13333 /*
13334 * Find delta after normalizing se's vruntime with its cfs_rq's
13335 * zero_vruntime_fi, which would have been updated in prior calls
13336 * to se_fi_update().
13337 */
13338 delta = (s64)(sea->vruntime - seb->vruntime) +
13339 (s64)(cfs_rqb->zero_vruntime_fi - cfs_rqa->zero_vruntime_fi);
13340
13341 return delta > 0;
13342 }
13343
task_is_throttled_fair(struct task_struct * p,int cpu)13344 static int task_is_throttled_fair(struct task_struct *p, int cpu)
13345 {
13346 struct cfs_rq *cfs_rq;
13347
13348 #ifdef CONFIG_FAIR_GROUP_SCHED
13349 cfs_rq = task_group(p)->cfs_rq[cpu];
13350 #else
13351 cfs_rq = &cpu_rq(cpu)->cfs;
13352 #endif
13353 return throttled_hierarchy(cfs_rq);
13354 }
13355 #else /* !CONFIG_SCHED_CORE: */
task_tick_core(struct rq * rq,struct task_struct * curr)13356 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
13357 #endif /* !CONFIG_SCHED_CORE */
13358
13359 /*
13360 * scheduler tick hitting a task of our scheduling class.
13361 *
13362 * NOTE: This function can be called remotely by the tick offload that
13363 * goes along full dynticks. Therefore no local assumption can be made
13364 * and everything must be accessed through the @rq and @curr passed in
13365 * parameters.
13366 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)13367 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
13368 {
13369 struct cfs_rq *cfs_rq;
13370 struct sched_entity *se = &curr->se;
13371
13372 for_each_sched_entity(se) {
13373 cfs_rq = cfs_rq_of(se);
13374 entity_tick(cfs_rq, se, queued);
13375 }
13376
13377 if (static_branch_unlikely(&sched_numa_balancing))
13378 task_tick_numa(rq, curr);
13379
13380 update_misfit_status(curr, rq);
13381 check_update_overutilized_status(task_rq(curr));
13382
13383 task_tick_core(rq, curr);
13384 }
13385
13386 /*
13387 * called on fork with the child task as argument from the parent's context
13388 * - child not yet on the tasklist
13389 * - preemption disabled
13390 */
task_fork_fair(struct task_struct * p)13391 static void task_fork_fair(struct task_struct *p)
13392 {
13393 set_task_max_allowed_capacity(p);
13394 }
13395
13396 /*
13397 * Priority of the task has changed. Check to see if we preempt
13398 * the current task.
13399 */
13400 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,u64 oldprio)13401 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio)
13402 {
13403 if (!task_on_rq_queued(p))
13404 return;
13405
13406 if (p->prio == oldprio)
13407 return;
13408
13409 if (rq->cfs.nr_queued == 1)
13410 return;
13411
13412 /*
13413 * Reschedule if we are currently running on this runqueue and
13414 * our priority decreased, or if we are not currently running on
13415 * this runqueue and our priority is higher than the current's
13416 */
13417 if (task_current_donor(rq, p)) {
13418 if (p->prio > oldprio)
13419 resched_curr(rq);
13420 } else {
13421 wakeup_preempt(rq, p, 0);
13422 }
13423 }
13424
13425 #ifdef CONFIG_FAIR_GROUP_SCHED
13426 /*
13427 * Propagate the changes of the sched_entity across the tg tree to make it
13428 * visible to the root
13429 */
propagate_entity_cfs_rq(struct sched_entity * se)13430 static void propagate_entity_cfs_rq(struct sched_entity *se)
13431 {
13432 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13433
13434 /*
13435 * If a task gets attached to this cfs_rq and before being queued,
13436 * it gets migrated to another CPU due to reasons like affinity
13437 * change, make sure this cfs_rq stays on leaf cfs_rq list to have
13438 * that removed load decayed or it can cause faireness problem.
13439 */
13440 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13441 list_add_leaf_cfs_rq(cfs_rq);
13442
13443 /* Start to propagate at parent */
13444 se = se->parent;
13445
13446 for_each_sched_entity(se) {
13447 cfs_rq = cfs_rq_of(se);
13448
13449 update_load_avg(cfs_rq, se, UPDATE_TG);
13450
13451 if (!cfs_rq_pelt_clock_throttled(cfs_rq))
13452 list_add_leaf_cfs_rq(cfs_rq);
13453 }
13454
13455 assert_list_leaf_cfs_rq(rq_of(cfs_rq));
13456 }
13457 #else /* !CONFIG_FAIR_GROUP_SCHED: */
propagate_entity_cfs_rq(struct sched_entity * se)13458 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
13459 #endif /* !CONFIG_FAIR_GROUP_SCHED */
13460
detach_entity_cfs_rq(struct sched_entity * se)13461 static void detach_entity_cfs_rq(struct sched_entity *se)
13462 {
13463 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13464
13465 /*
13466 * In case the task sched_avg hasn't been attached:
13467 * - A forked task which hasn't been woken up by wake_up_new_task().
13468 * - A task which has been woken up by try_to_wake_up() but is
13469 * waiting for actually being woken up by sched_ttwu_pending().
13470 */
13471 if (!se->avg.last_update_time)
13472 return;
13473
13474 /* Catch up with the cfs_rq and remove our load when we leave */
13475 update_load_avg(cfs_rq, se, 0);
13476 detach_entity_load_avg(cfs_rq, se);
13477 update_tg_load_avg(cfs_rq);
13478 propagate_entity_cfs_rq(se);
13479 }
13480
attach_entity_cfs_rq(struct sched_entity * se)13481 static void attach_entity_cfs_rq(struct sched_entity *se)
13482 {
13483 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13484
13485 /* Synchronize entity with its cfs_rq */
13486 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
13487 attach_entity_load_avg(cfs_rq, se);
13488 update_tg_load_avg(cfs_rq);
13489 propagate_entity_cfs_rq(se);
13490 }
13491
detach_task_cfs_rq(struct task_struct * p)13492 static void detach_task_cfs_rq(struct task_struct *p)
13493 {
13494 struct sched_entity *se = &p->se;
13495
13496 detach_entity_cfs_rq(se);
13497 }
13498
attach_task_cfs_rq(struct task_struct * p)13499 static void attach_task_cfs_rq(struct task_struct *p)
13500 {
13501 struct sched_entity *se = &p->se;
13502
13503 attach_entity_cfs_rq(se);
13504 }
13505
switching_from_fair(struct rq * rq,struct task_struct * p)13506 static void switching_from_fair(struct rq *rq, struct task_struct *p)
13507 {
13508 if (p->se.sched_delayed)
13509 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK);
13510 }
13511
switched_from_fair(struct rq * rq,struct task_struct * p)13512 static void switched_from_fair(struct rq *rq, struct task_struct *p)
13513 {
13514 detach_task_cfs_rq(p);
13515 }
13516
switched_to_fair(struct rq * rq,struct task_struct * p)13517 static void switched_to_fair(struct rq *rq, struct task_struct *p)
13518 {
13519 WARN_ON_ONCE(p->se.sched_delayed);
13520
13521 attach_task_cfs_rq(p);
13522
13523 set_task_max_allowed_capacity(p);
13524
13525 if (task_on_rq_queued(p)) {
13526 /*
13527 * We were most likely switched from sched_rt, so
13528 * kick off the schedule if running, otherwise just see
13529 * if we can still preempt the current task.
13530 */
13531 if (task_current_donor(rq, p))
13532 resched_curr(rq);
13533 else
13534 wakeup_preempt(rq, p, 0);
13535 }
13536 }
13537
__set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13538 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13539 {
13540 struct sched_entity *se = &p->se;
13541
13542 if (task_on_rq_queued(p)) {
13543 /*
13544 * Move the next running task to the front of the list, so our
13545 * cfs_tasks list becomes MRU one.
13546 */
13547 list_move(&se->group_node, &rq->cfs_tasks);
13548 }
13549 if (!first)
13550 return;
13551
13552 WARN_ON_ONCE(se->sched_delayed);
13553
13554 if (hrtick_enabled_fair(rq))
13555 hrtick_start_fair(rq, p);
13556
13557 update_misfit_status(p, rq);
13558 sched_fair_update_stop_tick(rq, p);
13559 }
13560
13561 /*
13562 * Account for a task changing its policy or group.
13563 *
13564 * This routine is mostly called to set cfs_rq->curr field when a task
13565 * migrates between groups/classes.
13566 */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)13567 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
13568 {
13569 struct sched_entity *se = &p->se;
13570
13571 for_each_sched_entity(se) {
13572 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13573
13574 set_next_entity(cfs_rq, se);
13575 /* ensure bandwidth has been allocated on our new cfs_rq */
13576 account_cfs_rq_runtime(cfs_rq, 0);
13577 }
13578
13579 __set_next_task_fair(rq, p, first);
13580 }
13581
init_cfs_rq(struct cfs_rq * cfs_rq)13582 void init_cfs_rq(struct cfs_rq *cfs_rq)
13583 {
13584 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
13585 cfs_rq->zero_vruntime = (u64)(-(1LL << 20));
13586 raw_spin_lock_init(&cfs_rq->removed.lock);
13587 }
13588
13589 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)13590 static void task_change_group_fair(struct task_struct *p)
13591 {
13592 /*
13593 * We couldn't detach or attach a forked task which
13594 * hasn't been woken up by wake_up_new_task().
13595 */
13596 if (READ_ONCE(p->__state) == TASK_NEW)
13597 return;
13598
13599 detach_task_cfs_rq(p);
13600
13601 /* Tell se's cfs_rq has been changed -- migrated */
13602 p->se.avg.last_update_time = 0;
13603 set_task_rq(p, task_cpu(p));
13604 attach_task_cfs_rq(p);
13605 }
13606
free_fair_sched_group(struct task_group * tg)13607 void free_fair_sched_group(struct task_group *tg)
13608 {
13609 int i;
13610
13611 for_each_possible_cpu(i) {
13612 if (tg->cfs_rq)
13613 kfree(tg->cfs_rq[i]);
13614 if (tg->se)
13615 kfree(tg->se[i]);
13616 }
13617
13618 kfree(tg->cfs_rq);
13619 kfree(tg->se);
13620 }
13621
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13622 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13623 {
13624 struct sched_entity *se;
13625 struct cfs_rq *cfs_rq;
13626 int i;
13627
13628 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
13629 if (!tg->cfs_rq)
13630 goto err;
13631 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
13632 if (!tg->se)
13633 goto err;
13634
13635 tg->shares = NICE_0_LOAD;
13636
13637 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
13638
13639 for_each_possible_cpu(i) {
13640 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
13641 GFP_KERNEL, cpu_to_node(i));
13642 if (!cfs_rq)
13643 goto err;
13644
13645 se = kzalloc_node(sizeof(struct sched_entity_stats),
13646 GFP_KERNEL, cpu_to_node(i));
13647 if (!se)
13648 goto err_free_rq;
13649
13650 init_cfs_rq(cfs_rq);
13651 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
13652 init_entity_runnable_average(se);
13653 }
13654
13655 return 1;
13656
13657 err_free_rq:
13658 kfree(cfs_rq);
13659 err:
13660 return 0;
13661 }
13662
online_fair_sched_group(struct task_group * tg)13663 void online_fair_sched_group(struct task_group *tg)
13664 {
13665 struct sched_entity *se;
13666 struct rq_flags rf;
13667 struct rq *rq;
13668 int i;
13669
13670 for_each_possible_cpu(i) {
13671 rq = cpu_rq(i);
13672 se = tg->se[i];
13673 rq_lock_irq(rq, &rf);
13674 update_rq_clock(rq);
13675 attach_entity_cfs_rq(se);
13676 sync_throttle(tg, i);
13677 rq_unlock_irq(rq, &rf);
13678 }
13679 }
13680
unregister_fair_sched_group(struct task_group * tg)13681 void unregister_fair_sched_group(struct task_group *tg)
13682 {
13683 int cpu;
13684
13685 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
13686
13687 for_each_possible_cpu(cpu) {
13688 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
13689 struct sched_entity *se = tg->se[cpu];
13690 struct rq *rq = cpu_rq(cpu);
13691
13692 if (se) {
13693 if (se->sched_delayed) {
13694 guard(rq_lock_irqsave)(rq);
13695 if (se->sched_delayed) {
13696 update_rq_clock(rq);
13697 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED);
13698 }
13699 list_del_leaf_cfs_rq(cfs_rq);
13700 }
13701 remove_entity_load_avg(se);
13702 }
13703
13704 /*
13705 * Only empty task groups can be destroyed; so we can speculatively
13706 * check on_list without danger of it being re-added.
13707 */
13708 if (cfs_rq->on_list) {
13709 guard(rq_lock_irqsave)(rq);
13710 list_del_leaf_cfs_rq(cfs_rq);
13711 }
13712 }
13713 }
13714
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)13715 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
13716 struct sched_entity *se, int cpu,
13717 struct sched_entity *parent)
13718 {
13719 struct rq *rq = cpu_rq(cpu);
13720
13721 cfs_rq->tg = tg;
13722 cfs_rq->rq = rq;
13723 init_cfs_rq_runtime(cfs_rq);
13724
13725 tg->cfs_rq[cpu] = cfs_rq;
13726 tg->se[cpu] = se;
13727
13728 /* se could be NULL for root_task_group */
13729 if (!se)
13730 return;
13731
13732 if (!parent) {
13733 se->cfs_rq = &rq->cfs;
13734 se->depth = 0;
13735 } else {
13736 se->cfs_rq = parent->my_q;
13737 se->depth = parent->depth + 1;
13738 }
13739
13740 se->my_q = cfs_rq;
13741 /* guarantee group entities always have weight */
13742 update_load_set(&se->load, NICE_0_LOAD);
13743 se->parent = parent;
13744 }
13745
13746 static DEFINE_MUTEX(shares_mutex);
13747
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13748 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13749 {
13750 int i;
13751
13752 lockdep_assert_held(&shares_mutex);
13753
13754 /*
13755 * We can't change the weight of the root cgroup.
13756 */
13757 if (!tg->se[0])
13758 return -EINVAL;
13759
13760 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13761
13762 if (tg->shares == shares)
13763 return 0;
13764
13765 tg->shares = shares;
13766 for_each_possible_cpu(i) {
13767 struct rq *rq = cpu_rq(i);
13768 struct sched_entity *se = tg->se[i];
13769 struct rq_flags rf;
13770
13771 /* Propagate contribution to hierarchy */
13772 rq_lock_irqsave(rq, &rf);
13773 update_rq_clock(rq);
13774 for_each_sched_entity(se) {
13775 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13776 update_cfs_group(se);
13777 }
13778 rq_unlock_irqrestore(rq, &rf);
13779 }
13780
13781 return 0;
13782 }
13783
sched_group_set_shares(struct task_group * tg,unsigned long shares)13784 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13785 {
13786 int ret;
13787
13788 mutex_lock(&shares_mutex);
13789 if (tg_is_idle(tg))
13790 ret = -EINVAL;
13791 else
13792 ret = __sched_group_set_shares(tg, shares);
13793 mutex_unlock(&shares_mutex);
13794
13795 return ret;
13796 }
13797
sched_group_set_idle(struct task_group * tg,long idle)13798 int sched_group_set_idle(struct task_group *tg, long idle)
13799 {
13800 int i;
13801
13802 if (tg == &root_task_group)
13803 return -EINVAL;
13804
13805 if (idle < 0 || idle > 1)
13806 return -EINVAL;
13807
13808 mutex_lock(&shares_mutex);
13809
13810 if (tg->idle == idle) {
13811 mutex_unlock(&shares_mutex);
13812 return 0;
13813 }
13814
13815 tg->idle = idle;
13816
13817 for_each_possible_cpu(i) {
13818 struct rq *rq = cpu_rq(i);
13819 struct sched_entity *se = tg->se[i];
13820 struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i];
13821 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13822 long idle_task_delta;
13823 struct rq_flags rf;
13824
13825 rq_lock_irqsave(rq, &rf);
13826
13827 grp_cfs_rq->idle = idle;
13828 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13829 goto next_cpu;
13830
13831 idle_task_delta = grp_cfs_rq->h_nr_queued -
13832 grp_cfs_rq->h_nr_idle;
13833 if (!cfs_rq_is_idle(grp_cfs_rq))
13834 idle_task_delta *= -1;
13835
13836 for_each_sched_entity(se) {
13837 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13838
13839 if (!se->on_rq)
13840 break;
13841
13842 cfs_rq->h_nr_idle += idle_task_delta;
13843
13844 /* Already accounted at parent level and above. */
13845 if (cfs_rq_is_idle(cfs_rq))
13846 break;
13847 }
13848
13849 next_cpu:
13850 rq_unlock_irqrestore(rq, &rf);
13851 }
13852
13853 /* Idle groups have minimum weight. */
13854 if (tg_is_idle(tg))
13855 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13856 else
13857 __sched_group_set_shares(tg, NICE_0_LOAD);
13858
13859 mutex_unlock(&shares_mutex);
13860 return 0;
13861 }
13862
13863 #endif /* CONFIG_FAIR_GROUP_SCHED */
13864
13865
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13866 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13867 {
13868 struct sched_entity *se = &task->se;
13869 unsigned int rr_interval = 0;
13870
13871 /*
13872 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13873 * idle runqueue:
13874 */
13875 if (rq->cfs.load.weight)
13876 rr_interval = NS_TO_JIFFIES(se->slice);
13877
13878 return rr_interval;
13879 }
13880
13881 /*
13882 * All the scheduling class methods:
13883 */
13884 DEFINE_SCHED_CLASS(fair) = {
13885
13886 .queue_mask = 2,
13887
13888 .enqueue_task = enqueue_task_fair,
13889 .dequeue_task = dequeue_task_fair,
13890 .yield_task = yield_task_fair,
13891 .yield_to_task = yield_to_task_fair,
13892
13893 .wakeup_preempt = check_preempt_wakeup_fair,
13894
13895 .pick_task = pick_task_fair,
13896 .pick_next_task = pick_next_task_fair,
13897 .put_prev_task = put_prev_task_fair,
13898 .set_next_task = set_next_task_fair,
13899
13900 .select_task_rq = select_task_rq_fair,
13901 .migrate_task_rq = migrate_task_rq_fair,
13902
13903 .rq_online = rq_online_fair,
13904 .rq_offline = rq_offline_fair,
13905
13906 .task_dead = task_dead_fair,
13907 .set_cpus_allowed = set_cpus_allowed_fair,
13908
13909 .task_tick = task_tick_fair,
13910 .task_fork = task_fork_fair,
13911
13912 .reweight_task = reweight_task_fair,
13913 .prio_changed = prio_changed_fair,
13914 .switching_from = switching_from_fair,
13915 .switched_from = switched_from_fair,
13916 .switched_to = switched_to_fair,
13917
13918 .get_rr_interval = get_rr_interval_fair,
13919
13920 .update_curr = update_curr_fair,
13921
13922 #ifdef CONFIG_FAIR_GROUP_SCHED
13923 .task_change_group = task_change_group_fair,
13924 #endif
13925
13926 #ifdef CONFIG_SCHED_CORE
13927 .task_is_throttled = task_is_throttled_fair,
13928 #endif
13929
13930 #ifdef CONFIG_UCLAMP_TASK
13931 .uclamp_enabled = 1,
13932 #endif
13933 };
13934
print_cfs_stats(struct seq_file * m,int cpu)13935 void print_cfs_stats(struct seq_file *m, int cpu)
13936 {
13937 struct cfs_rq *cfs_rq, *pos;
13938
13939 rcu_read_lock();
13940 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13941 print_cfs_rq(m, cpu, cfs_rq);
13942 rcu_read_unlock();
13943 }
13944
13945 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13946 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13947 {
13948 int node;
13949 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13950 struct numa_group *ng;
13951
13952 rcu_read_lock();
13953 ng = rcu_dereference(p->numa_group);
13954 for_each_online_node(node) {
13955 if (p->numa_faults) {
13956 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13957 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13958 }
13959 if (ng) {
13960 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13961 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13962 }
13963 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13964 }
13965 rcu_read_unlock();
13966 }
13967 #endif /* CONFIG_NUMA_BALANCING */
13968
init_sched_fair_class(void)13969 __init void init_sched_fair_class(void)
13970 {
13971 int i;
13972
13973 for_each_possible_cpu(i) {
13974 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13975 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
13976 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13977 GFP_KERNEL, cpu_to_node(i));
13978
13979 #ifdef CONFIG_CFS_BANDWIDTH
13980 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13981 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13982 #endif
13983 }
13984
13985 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq);
13986
13987 #ifdef CONFIG_NO_HZ_COMMON
13988 nohz.next_balance = jiffies;
13989 nohz.next_blocked = jiffies;
13990 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13991 #endif
13992 }
13993