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
41 #include <linux/cpuidle.h>
42 #include <linux/interrupt.h>
43 #include <linux/memory-tiers.h>
44 #include <linux/mempolicy.h>
45 #include <linux/mutex_api.h>
46 #include <linux/profile.h>
47 #include <linux/psi.h>
48 #include <linux/ratelimit.h>
49 #include <linux/task_work.h>
50 #include <linux/rbtree_augmented.h>
51
52 #include <asm/switch_to.h>
53
54 #include <linux/sched/cond_resched.h>
55
56 #include "sched.h"
57 #include "stats.h"
58 #include "autogroup.h"
59
60 /*
61 * Targeted preemption latency for CPU-bound tasks:
62 *
63 * NOTE: this latency value is not the same as the concept of
64 * 'timeslice length' - timeslices in CFS are of variable length
65 * and have no persistent notion like in traditional, time-slice
66 * based scheduling concepts.
67 *
68 * (to see the precise effective timeslice length of your workload,
69 * run vmstat and monitor the context-switches (cs) field)
70 *
71 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
72 */
73 unsigned int sysctl_sched_latency = 6000000ULL;
74 static unsigned int normalized_sysctl_sched_latency = 6000000ULL;
75
76 /*
77 * The initial- and re-scaling of tunables is configurable
78 *
79 * Options are:
80 *
81 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
82 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
83 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
84 *
85 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
86 */
87 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG;
88
89 /*
90 * Minimal preemption granularity for CPU-bound tasks:
91 *
92 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
93 */
94 unsigned int sysctl_sched_base_slice = 750000ULL;
95 static unsigned int normalized_sysctl_sched_base_slice = 750000ULL;
96
97 /*
98 * This value is kept at sysctl_sched_latency/sysctl_sched_min_granularity
99 */
100 static unsigned int sched_nr_latency = 8;
101
102 /*
103 * After fork, child runs first. If set to 0 (default) then
104 * parent will (try to) run first.
105 */
106 unsigned int sysctl_sched_child_runs_first __read_mostly;
107
108 /*
109 * SCHED_OTHER wake-up granularity.
110 *
111 * This option delays the preemption effects of decoupled workloads
112 * and reduces their over-scheduling. Synchronous workloads will still
113 * have immediate wakeup/sleep latencies.
114 *
115 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
116 */
117 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
118 static unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
119
120 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
121
122 int sched_thermal_decay_shift;
setup_sched_thermal_decay_shift(char * str)123 static int __init setup_sched_thermal_decay_shift(char *str)
124 {
125 int _shift = 0;
126
127 if (kstrtoint(str, 0, &_shift))
128 pr_warn("Unable to set scheduler thermal pressure decay shift parameter\n");
129
130 sched_thermal_decay_shift = clamp(_shift, 0, 10);
131 return 1;
132 }
133 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift);
134
135 #ifdef CONFIG_SMP
136 /*
137 * For asym packing, by default the lower numbered CPU has higher priority.
138 */
arch_asym_cpu_priority(int cpu)139 int __weak arch_asym_cpu_priority(int cpu)
140 {
141 return -cpu;
142 }
143
144 /*
145 * The margin used when comparing utilization with CPU capacity.
146 *
147 * (default: ~20%)
148 */
149 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024)
150
151 /*
152 * The margin used when comparing CPU capacities.
153 * is 'cap1' noticeably greater than 'cap2'
154 *
155 * (default: ~5%)
156 */
157 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078)
158 #endif
159
160 #ifdef CONFIG_CFS_BANDWIDTH
161 /*
162 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
163 * each time a cfs_rq requests quota.
164 *
165 * Note: in the case that the slice exceeds the runtime remaining (either due
166 * to consumption or the quota being specified to be smaller than the slice)
167 * we will always only issue the remaining available time.
168 *
169 * (default: 5 msec, units: microseconds)
170 */
171 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
172 #endif
173
174 #ifdef CONFIG_NUMA_BALANCING
175 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */
176 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536;
177 #endif
178
179 #ifdef CONFIG_SYSCTL
180 static struct ctl_table sched_fair_sysctls[] = {
181 {
182 .procname = "sched_child_runs_first",
183 .data = &sysctl_sched_child_runs_first,
184 .maxlen = sizeof(unsigned int),
185 .mode = 0644,
186 .proc_handler = proc_dointvec,
187 },
188 #ifdef CONFIG_CFS_BANDWIDTH
189 {
190 .procname = "sched_cfs_bandwidth_slice_us",
191 .data = &sysctl_sched_cfs_bandwidth_slice,
192 .maxlen = sizeof(unsigned int),
193 .mode = 0644,
194 .proc_handler = proc_dointvec_minmax,
195 .extra1 = SYSCTL_ONE,
196 },
197 #endif
198 #ifdef CONFIG_NUMA_BALANCING
199 {
200 .procname = "numa_balancing_promote_rate_limit_MBps",
201 .data = &sysctl_numa_balancing_promote_rate_limit,
202 .maxlen = sizeof(unsigned int),
203 .mode = 0644,
204 .proc_handler = proc_dointvec_minmax,
205 .extra1 = SYSCTL_ZERO,
206 },
207 #endif /* CONFIG_NUMA_BALANCING */
208 {}
209 };
210
sched_fair_sysctl_init(void)211 static int __init sched_fair_sysctl_init(void)
212 {
213 register_sysctl_init("kernel", sched_fair_sysctls);
214 return 0;
215 }
216 late_initcall(sched_fair_sysctl_init);
217 #endif
218
update_load_add(struct load_weight * lw,unsigned long inc)219 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
220 {
221 lw->weight += inc;
222 lw->inv_weight = 0;
223 }
224
update_load_sub(struct load_weight * lw,unsigned long dec)225 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
226 {
227 lw->weight -= dec;
228 lw->inv_weight = 0;
229 }
230
update_load_set(struct load_weight * lw,unsigned long w)231 static inline void update_load_set(struct load_weight *lw, unsigned long w)
232 {
233 lw->weight = w;
234 lw->inv_weight = 0;
235 }
236
237 /*
238 * Increase the granularity value when there are more CPUs,
239 * because with more CPUs the 'effective latency' as visible
240 * to users decreases. But the relationship is not linear,
241 * so pick a second-best guess by going with the log2 of the
242 * number of CPUs.
243 *
244 * This idea comes from the SD scheduler of Con Kolivas:
245 */
get_update_sysctl_factor(void)246 static unsigned int get_update_sysctl_factor(void)
247 {
248 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8);
249 unsigned int factor;
250
251 switch (sysctl_sched_tunable_scaling) {
252 case SCHED_TUNABLESCALING_NONE:
253 factor = 1;
254 break;
255 case SCHED_TUNABLESCALING_LINEAR:
256 factor = cpus;
257 break;
258 case SCHED_TUNABLESCALING_LOG:
259 default:
260 factor = 1 + ilog2(cpus);
261 break;
262 }
263
264 return factor;
265 }
266
update_sysctl(void)267 static void update_sysctl(void)
268 {
269 unsigned int factor = get_update_sysctl_factor();
270
271 #define SET_SYSCTL(name) \
272 (sysctl_##name = (factor) * normalized_sysctl_##name)
273 SET_SYSCTL(sched_base_slice);
274 SET_SYSCTL(sched_latency);
275 SET_SYSCTL(sched_wakeup_granularity);
276 #undef SET_SYSCTL
277 }
278
sched_init_granularity(void)279 void __init sched_init_granularity(void)
280 {
281 update_sysctl();
282 }
283
284 #define WMULT_CONST (~0U)
285 #define WMULT_SHIFT 32
286
__update_inv_weight(struct load_weight * lw)287 static void __update_inv_weight(struct load_weight *lw)
288 {
289 unsigned long w;
290
291 if (likely(lw->inv_weight))
292 return;
293
294 w = scale_load_down(lw->weight);
295
296 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
297 lw->inv_weight = 1;
298 else if (unlikely(!w))
299 lw->inv_weight = WMULT_CONST;
300 else
301 lw->inv_weight = WMULT_CONST / w;
302 }
303
304 /*
305 * delta_exec * weight / lw.weight
306 * OR
307 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
308 *
309 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case
310 * we're guaranteed shift stays positive because inv_weight is guaranteed to
311 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
312 *
313 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
314 * weight/lw.weight <= 1, and therefore our shift will also be positive.
315 */
__calc_delta(u64 delta_exec,unsigned long weight,struct load_weight * lw)316 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
317 {
318 u64 fact = scale_load_down(weight);
319 u32 fact_hi = (u32)(fact >> 32);
320 int shift = WMULT_SHIFT;
321 int fs;
322
323 __update_inv_weight(lw);
324
325 if (unlikely(fact_hi)) {
326 fs = fls(fact_hi);
327 shift -= fs;
328 fact >>= fs;
329 }
330
331 fact = mul_u32_u32(fact, lw->inv_weight);
332
333 fact_hi = (u32)(fact >> 32);
334 if (fact_hi) {
335 fs = fls(fact_hi);
336 shift -= fs;
337 fact >>= fs;
338 }
339
340 return mul_u64_u32_shr(delta_exec, fact, shift);
341 }
342
343 /*
344 * delta /= w
345 */
calc_delta_fair(u64 delta,struct sched_entity * se)346 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
347 {
348 if (unlikely(se->load.weight != NICE_0_LOAD))
349 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
350
351 return delta;
352 }
353
354 const struct sched_class fair_sched_class;
355
356 /**************************************************************
357 * CFS operations on generic schedulable entities:
358 */
359
360 #ifdef CONFIG_FAIR_GROUP_SCHED
361
362 /* Walk up scheduling entities hierarchy */
363 #define for_each_sched_entity(se) \
364 for (; se; se = se->parent)
365
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)366 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
367 {
368 struct rq *rq = rq_of(cfs_rq);
369 int cpu = cpu_of(rq);
370
371 if (cfs_rq->on_list)
372 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list;
373
374 cfs_rq->on_list = 1;
375
376 /*
377 * Ensure we either appear before our parent (if already
378 * enqueued) or force our parent to appear after us when it is
379 * enqueued. The fact that we always enqueue bottom-up
380 * reduces this to two cases and a special case for the root
381 * cfs_rq. Furthermore, it also means that we will always reset
382 * tmp_alone_branch either when the branch is connected
383 * to a tree or when we reach the top of the tree
384 */
385 if (cfs_rq->tg->parent &&
386 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) {
387 /*
388 * If parent is already on the list, we add the child
389 * just before. Thanks to circular linked property of
390 * the list, this means to put the child at the tail
391 * of the list that starts by parent.
392 */
393 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
394 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list));
395 /*
396 * The branch is now connected to its tree so we can
397 * reset tmp_alone_branch to the beginning of the
398 * list.
399 */
400 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
401 return true;
402 }
403
404 if (!cfs_rq->tg->parent) {
405 /*
406 * cfs rq without parent should be put
407 * at the tail of the list.
408 */
409 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
410 &rq->leaf_cfs_rq_list);
411 /*
412 * We have reach the top of a tree so we can reset
413 * tmp_alone_branch to the beginning of the list.
414 */
415 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
416 return true;
417 }
418
419 /*
420 * The parent has not already been added so we want to
421 * make sure that it will be put after us.
422 * tmp_alone_branch points to the begin of the branch
423 * where we will add parent.
424 */
425 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch);
426 /*
427 * update tmp_alone_branch to points to the new begin
428 * of the branch
429 */
430 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list;
431 return false;
432 }
433
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)434 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
435 {
436 if (cfs_rq->on_list) {
437 struct rq *rq = rq_of(cfs_rq);
438
439 /*
440 * With cfs_rq being unthrottled/throttled during an enqueue,
441 * it can happen the tmp_alone_branch points the a leaf that
442 * we finally want to del. In this case, tmp_alone_branch moves
443 * to the prev element but it will point to rq->leaf_cfs_rq_list
444 * at the end of the enqueue.
445 */
446 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list)
447 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev;
448
449 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
450 cfs_rq->on_list = 0;
451 }
452 }
453
assert_list_leaf_cfs_rq(struct rq * rq)454 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
455 {
456 SCHED_WARN_ON(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list);
457 }
458
459 /* Iterate thr' all leaf cfs_rq's on a runqueue */
460 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
461 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \
462 leaf_cfs_rq_list)
463
464 /* Do the two (enqueued) entities belong to the same group ? */
465 static inline struct cfs_rq *
is_same_group(struct sched_entity * se,struct sched_entity * pse)466 is_same_group(struct sched_entity *se, struct sched_entity *pse)
467 {
468 if (se->cfs_rq == pse->cfs_rq)
469 return se->cfs_rq;
470
471 return NULL;
472 }
473
parent_entity(const struct sched_entity * se)474 static inline struct sched_entity *parent_entity(const struct sched_entity *se)
475 {
476 return se->parent;
477 }
478
479 static void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)480 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
481 {
482 int se_depth, pse_depth;
483
484 /*
485 * preemption test can be made between sibling entities who are in the
486 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
487 * both tasks until we find their ancestors who are siblings of common
488 * parent.
489 */
490
491 /* First walk up until both entities are at same depth */
492 se_depth = (*se)->depth;
493 pse_depth = (*pse)->depth;
494
495 while (se_depth > pse_depth) {
496 se_depth--;
497 *se = parent_entity(*se);
498 }
499
500 while (pse_depth > se_depth) {
501 pse_depth--;
502 *pse = parent_entity(*pse);
503 }
504
505 while (!is_same_group(*se, *pse)) {
506 *se = parent_entity(*se);
507 *pse = parent_entity(*pse);
508 }
509 }
510
tg_is_idle(struct task_group * tg)511 static int tg_is_idle(struct task_group *tg)
512 {
513 return tg->idle > 0;
514 }
515
cfs_rq_is_idle(struct cfs_rq * cfs_rq)516 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
517 {
518 return cfs_rq->idle > 0;
519 }
520
se_is_idle(struct sched_entity * se)521 static int se_is_idle(struct sched_entity *se)
522 {
523 if (entity_is_task(se))
524 return task_has_idle_policy(task_of(se));
525 return cfs_rq_is_idle(group_cfs_rq(se));
526 }
527
528 #else /* !CONFIG_FAIR_GROUP_SCHED */
529
530 #define for_each_sched_entity(se) \
531 for (; se; se = NULL)
532
list_add_leaf_cfs_rq(struct cfs_rq * cfs_rq)533 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
534 {
535 return true;
536 }
537
list_del_leaf_cfs_rq(struct cfs_rq * cfs_rq)538 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
539 {
540 }
541
assert_list_leaf_cfs_rq(struct rq * rq)542 static inline void assert_list_leaf_cfs_rq(struct rq *rq)
543 {
544 }
545
546 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \
547 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos)
548
parent_entity(struct sched_entity * se)549 static inline struct sched_entity *parent_entity(struct sched_entity *se)
550 {
551 return NULL;
552 }
553
554 static inline void
find_matching_se(struct sched_entity ** se,struct sched_entity ** pse)555 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
556 {
557 }
558
tg_is_idle(struct task_group * tg)559 static inline int tg_is_idle(struct task_group *tg)
560 {
561 return 0;
562 }
563
cfs_rq_is_idle(struct cfs_rq * cfs_rq)564 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq)
565 {
566 return 0;
567 }
568
se_is_idle(struct sched_entity * se)569 static int se_is_idle(struct sched_entity *se)
570 {
571 return 0;
572 }
573
574 #endif /* CONFIG_FAIR_GROUP_SCHED */
575
576 static __always_inline
577 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
578
579 /**************************************************************
580 * Scheduling class tree data structure manipulation methods:
581 */
582
max_vruntime(u64 max_vruntime,u64 vruntime)583 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
584 {
585 s64 delta = (s64)(vruntime - max_vruntime);
586 if (delta > 0)
587 max_vruntime = vruntime;
588
589 return max_vruntime;
590 }
591
min_vruntime(u64 min_vruntime,u64 vruntime)592 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
593 {
594 s64 delta = (s64)(vruntime - min_vruntime);
595 if (delta < 0)
596 min_vruntime = vruntime;
597
598 return min_vruntime;
599 }
600
entity_before(const struct sched_entity * a,const struct sched_entity * b)601 static inline bool entity_before(const struct sched_entity *a,
602 const struct sched_entity *b)
603 {
604 return (s64)(a->vruntime - b->vruntime) < 0;
605 }
606
entity_key(struct cfs_rq * cfs_rq,struct sched_entity * se)607 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se)
608 {
609 return (s64)(se->vruntime - cfs_rq->min_vruntime);
610 }
611
612 #define __node_2_se(node) \
613 rb_entry((node), struct sched_entity, run_node)
614
615 /*
616 * Compute virtual time from the per-task service numbers:
617 *
618 * Fair schedulers conserve lag:
619 *
620 * \Sum lag_i = 0
621 *
622 * Where lag_i is given by:
623 *
624 * lag_i = S - s_i = w_i * (V - v_i)
625 *
626 * Where S is the ideal service time and V is it's virtual time counterpart.
627 * Therefore:
628 *
629 * \Sum lag_i = 0
630 * \Sum w_i * (V - v_i) = 0
631 * \Sum w_i * V - w_i * v_i = 0
632 *
633 * From which we can solve an expression for V in v_i (which we have in
634 * se->vruntime):
635 *
636 * \Sum v_i * w_i \Sum v_i * w_i
637 * V = -------------- = --------------
638 * \Sum w_i W
639 *
640 * Specifically, this is the weighted average of all entity virtual runtimes.
641 *
642 * [[ NOTE: this is only equal to the ideal scheduler under the condition
643 * that join/leave operations happen at lag_i = 0, otherwise the
644 * virtual time has non-continguous motion equivalent to:
645 *
646 * V +-= lag_i / W
647 *
648 * Also see the comment in place_entity() that deals with this. ]]
649 *
650 * However, since v_i is u64, and the multiplcation could easily overflow
651 * transform it into a relative form that uses smaller quantities:
652 *
653 * Substitute: v_i == (v_i - v0) + v0
654 *
655 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i
656 * V = ---------------------------- = --------------------- + v0
657 * W W
658 *
659 * Which we track using:
660 *
661 * v0 := cfs_rq->min_vruntime
662 * \Sum (v_i - v0) * w_i := cfs_rq->avg_vruntime
663 * \Sum w_i := cfs_rq->avg_load
664 *
665 * Since min_vruntime is a monotonic increasing variable that closely tracks
666 * the per-task service, these deltas: (v_i - v), will be in the order of the
667 * maximal (virtual) lag induced in the system due to quantisation.
668 *
669 * Also, we use scale_load_down() to reduce the size.
670 *
671 * As measured, the max (key * weight) value was ~44 bits for a kernel build.
672 */
673 static void
avg_vruntime_add(struct cfs_rq * cfs_rq,struct sched_entity * se)674 avg_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se)
675 {
676 unsigned long weight = scale_load_down(se->load.weight);
677 s64 key = entity_key(cfs_rq, se);
678
679 cfs_rq->avg_vruntime += key * weight;
680 cfs_rq->avg_load += weight;
681 }
682
683 static void
avg_vruntime_sub(struct cfs_rq * cfs_rq,struct sched_entity * se)684 avg_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se)
685 {
686 unsigned long weight = scale_load_down(se->load.weight);
687 s64 key = entity_key(cfs_rq, se);
688
689 cfs_rq->avg_vruntime -= key * weight;
690 cfs_rq->avg_load -= weight;
691 }
692
693 static inline
avg_vruntime_update(struct cfs_rq * cfs_rq,s64 delta)694 void avg_vruntime_update(struct cfs_rq *cfs_rq, s64 delta)
695 {
696 /*
697 * v' = v + d ==> avg_vruntime' = avg_runtime - d*avg_load
698 */
699 cfs_rq->avg_vruntime -= cfs_rq->avg_load * delta;
700 }
701
702 /*
703 * Specifically: avg_runtime() + 0 must result in entity_eligible() := true
704 * For this to be so, the result of this function must have a left bias.
705 */
avg_vruntime(struct cfs_rq * cfs_rq)706 u64 avg_vruntime(struct cfs_rq *cfs_rq)
707 {
708 struct sched_entity *curr = cfs_rq->curr;
709 s64 avg = cfs_rq->avg_vruntime;
710 long load = cfs_rq->avg_load;
711
712 if (curr && curr->on_rq) {
713 unsigned long weight = scale_load_down(curr->load.weight);
714
715 avg += entity_key(cfs_rq, curr) * weight;
716 load += weight;
717 }
718
719 if (load) {
720 /* sign flips effective floor / ceil */
721 if (avg < 0)
722 avg -= (load - 1);
723 avg = div_s64(avg, load);
724 }
725
726 return cfs_rq->min_vruntime + avg;
727 }
728
729 /*
730 * lag_i = S - s_i = w_i * (V - v_i)
731 *
732 * However, since V is approximated by the weighted average of all entities it
733 * is possible -- by addition/removal/reweight to the tree -- to move V around
734 * and end up with a larger lag than we started with.
735 *
736 * Limit this to either double the slice length with a minimum of TICK_NSEC
737 * since that is the timing granularity.
738 *
739 * EEVDF gives the following limit for a steady state system:
740 *
741 * -r_max < lag < max(r_max, q)
742 *
743 * XXX could add max_slice to the augmented data to track this.
744 */
update_entity_lag(struct cfs_rq * cfs_rq,struct sched_entity * se)745 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se)
746 {
747 s64 lag, limit;
748
749 SCHED_WARN_ON(!se->on_rq);
750 lag = avg_vruntime(cfs_rq) - se->vruntime;
751
752 limit = calc_delta_fair(max_t(u64, 2*se->slice, TICK_NSEC), se);
753 se->vlag = clamp(lag, -limit, limit);
754 }
755
756 /*
757 * Entity is eligible once it received less service than it ought to have,
758 * eg. lag >= 0.
759 *
760 * lag_i = S - s_i = w_i*(V - v_i)
761 *
762 * lag_i >= 0 -> V >= v_i
763 *
764 * \Sum (v_i - v)*w_i
765 * V = ------------------ + v
766 * \Sum w_i
767 *
768 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i)
769 *
770 * Note: using 'avg_vruntime() > se->vruntime' is inacurate due
771 * to the loss in precision caused by the division.
772 */
entity_eligible(struct cfs_rq * cfs_rq,struct sched_entity * se)773 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se)
774 {
775 struct sched_entity *curr = cfs_rq->curr;
776 s64 avg = cfs_rq->avg_vruntime;
777 long load = cfs_rq->avg_load;
778
779 if (curr && curr->on_rq) {
780 unsigned long weight = scale_load_down(curr->load.weight);
781
782 avg += entity_key(cfs_rq, curr) * weight;
783 load += weight;
784 }
785
786 return avg >= entity_key(cfs_rq, se) * load;
787 }
788
__update_min_vruntime(struct cfs_rq * cfs_rq,u64 vruntime)789 static u64 __update_min_vruntime(struct cfs_rq *cfs_rq, u64 vruntime)
790 {
791 u64 min_vruntime = cfs_rq->min_vruntime;
792 /*
793 * open coded max_vruntime() to allow updating avg_vruntime
794 */
795 s64 delta = (s64)(vruntime - min_vruntime);
796 if (delta > 0) {
797 avg_vruntime_update(cfs_rq, delta);
798 min_vruntime = vruntime;
799 }
800 return min_vruntime;
801 }
802
update_min_vruntime(struct cfs_rq * cfs_rq)803 static void update_min_vruntime(struct cfs_rq *cfs_rq)
804 {
805 struct sched_entity *se = __pick_first_entity(cfs_rq);
806 struct sched_entity *curr = cfs_rq->curr;
807
808 u64 vruntime = cfs_rq->min_vruntime;
809
810 if (curr) {
811 if (curr->on_rq)
812 vruntime = curr->vruntime;
813 else
814 curr = NULL;
815 }
816
817 if (se) {
818 if (!curr)
819 vruntime = se->vruntime;
820 else
821 vruntime = min_vruntime(vruntime, se->vruntime);
822 }
823
824 /* ensure we never gain time by being placed backwards. */
825 u64_u32_store(cfs_rq->min_vruntime,
826 __update_min_vruntime(cfs_rq, vruntime));
827 }
828
__entity_less(struct rb_node * a,const struct rb_node * b)829 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b)
830 {
831 return entity_before(__node_2_se(a), __node_2_se(b));
832 }
833
834 #define deadline_gt(field, lse, rse) ({ (s64)((lse)->field - (rse)->field) > 0; })
835
__update_min_deadline(struct sched_entity * se,struct rb_node * node)836 static inline void __update_min_deadline(struct sched_entity *se, struct rb_node *node)
837 {
838 if (node) {
839 struct sched_entity *rse = __node_2_se(node);
840 if (deadline_gt(min_deadline, se, rse))
841 se->min_deadline = rse->min_deadline;
842 }
843 }
844
845 /*
846 * se->min_deadline = min(se->deadline, left->min_deadline, right->min_deadline)
847 */
min_deadline_update(struct sched_entity * se,bool exit)848 static inline bool min_deadline_update(struct sched_entity *se, bool exit)
849 {
850 u64 old_min_deadline = se->min_deadline;
851 struct rb_node *node = &se->run_node;
852
853 se->min_deadline = se->deadline;
854 __update_min_deadline(se, node->rb_right);
855 __update_min_deadline(se, node->rb_left);
856
857 return se->min_deadline == old_min_deadline;
858 }
859
860 RB_DECLARE_CALLBACKS(static, min_deadline_cb, struct sched_entity,
861 run_node, min_deadline, min_deadline_update);
862
863 /*
864 * Enqueue an entity into the rb-tree:
865 */
__enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)866 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
867 {
868 avg_vruntime_add(cfs_rq, se);
869 se->min_deadline = se->deadline;
870 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
871 __entity_less, &min_deadline_cb);
872 }
873
__dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)874 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
875 {
876 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline,
877 &min_deadline_cb);
878 avg_vruntime_sub(cfs_rq, se);
879 }
880
__pick_first_entity(struct cfs_rq * cfs_rq)881 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
882 {
883 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline);
884
885 if (!left)
886 return NULL;
887
888 return __node_2_se(left);
889 }
890
891 /*
892 * Earliest Eligible Virtual Deadline First
893 *
894 * In order to provide latency guarantees for different request sizes
895 * EEVDF selects the best runnable task from two criteria:
896 *
897 * 1) the task must be eligible (must be owed service)
898 *
899 * 2) from those tasks that meet 1), we select the one
900 * with the earliest virtual deadline.
901 *
902 * We can do this in O(log n) time due to an augmented RB-tree. The
903 * tree keeps the entries sorted on service, but also functions as a
904 * heap based on the deadline by keeping:
905 *
906 * se->min_deadline = min(se->deadline, se->{left,right}->min_deadline)
907 *
908 * Which allows an EDF like search on (sub)trees.
909 */
__pick_eevdf(struct cfs_rq * cfs_rq)910 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq)
911 {
912 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node;
913 struct sched_entity *curr = cfs_rq->curr;
914 struct sched_entity *best = NULL;
915 struct sched_entity *best_left = NULL;
916
917 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr)))
918 curr = NULL;
919 best = curr;
920
921 /*
922 * Once selected, run a task until it either becomes non-eligible or
923 * until it gets a new slice. See the HACK in set_next_entity().
924 */
925 if (sched_feat(RUN_TO_PARITY) && curr && curr->vlag == curr->deadline)
926 return curr;
927
928 while (node) {
929 struct sched_entity *se = __node_2_se(node);
930
931 /*
932 * If this entity is not eligible, try the left subtree.
933 */
934 if (!entity_eligible(cfs_rq, se)) {
935 node = node->rb_left;
936 continue;
937 }
938
939 /*
940 * Now we heap search eligible trees for the best (min_)deadline
941 */
942 if (!best || deadline_gt(deadline, best, se))
943 best = se;
944
945 /*
946 * Every se in a left branch is eligible, keep track of the
947 * branch with the best min_deadline
948 */
949 if (node->rb_left) {
950 struct sched_entity *left = __node_2_se(node->rb_left);
951
952 if (!best_left || deadline_gt(min_deadline, best_left, left))
953 best_left = left;
954
955 /*
956 * min_deadline is in the left branch. rb_left and all
957 * descendants are eligible, so immediately switch to the second
958 * loop.
959 */
960 if (left->min_deadline == se->min_deadline)
961 break;
962 }
963
964 /* min_deadline is at this node, no need to look right */
965 if (se->deadline == se->min_deadline)
966 break;
967
968 /* else min_deadline is in the right branch. */
969 node = node->rb_right;
970 }
971
972 /*
973 * We ran into an eligible node which is itself the best.
974 * (Or nr_running == 0 and both are NULL)
975 */
976 if (!best_left || (s64)(best_left->min_deadline - best->deadline) > 0)
977 return best;
978
979 /*
980 * Now best_left and all of its children are eligible, and we are just
981 * looking for deadline == min_deadline
982 */
983 node = &best_left->run_node;
984 while (node) {
985 struct sched_entity *se = __node_2_se(node);
986
987 /* min_deadline is the current node */
988 if (se->deadline == se->min_deadline)
989 return se;
990
991 /* min_deadline is in the left branch */
992 if (node->rb_left &&
993 __node_2_se(node->rb_left)->min_deadline == se->min_deadline) {
994 node = node->rb_left;
995 continue;
996 }
997
998 /* else min_deadline is in the right branch */
999 node = node->rb_right;
1000 }
1001 return NULL;
1002 }
1003
pick_eevdf(struct cfs_rq * cfs_rq)1004 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq)
1005 {
1006 struct sched_entity *se = __pick_eevdf(cfs_rq);
1007
1008 if (!se) {
1009 struct sched_entity *left = __pick_first_entity(cfs_rq);
1010 if (left) {
1011 pr_err("EEVDF scheduling fail, picking leftmost\n");
1012 return left;
1013 }
1014 }
1015
1016 return se;
1017 }
1018
1019 #ifdef CONFIG_SCHED_DEBUG
__pick_last_entity(struct cfs_rq * cfs_rq)1020 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
1021 {
1022 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root);
1023
1024 if (!last)
1025 return NULL;
1026
1027 return __node_2_se(last);
1028 }
1029
1030 /**************************************************************
1031 * Scheduling class statistics methods:
1032 */
1033 #ifdef CONFIG_SMP
sched_update_scaling(void)1034 int sched_update_scaling(void)
1035 {
1036 unsigned int factor = get_update_sysctl_factor();
1037
1038 #define WRT_SYSCTL(name) \
1039 (normalized_sysctl_##name = sysctl_##name / (factor))
1040 WRT_SYSCTL(sched_base_slice);
1041 WRT_SYSCTL(sched_latency);
1042 WRT_SYSCTL(sched_wakeup_granularity);
1043 #undef WRT_SYSCTL
1044
1045 return 0;
1046 }
1047 #endif
1048 #endif
1049
1050 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se);
1051
1052 /*
1053 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i
1054 * this is probably good enough.
1055 */
update_deadline(struct cfs_rq * cfs_rq,struct sched_entity * se)1056 static void update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se)
1057 {
1058 if ((s64)(se->vruntime - se->deadline) < 0)
1059 return;
1060
1061 /*
1062 * For EEVDF the virtual time slope is determined by w_i (iow.
1063 * nice) while the request time r_i is determined by
1064 * sysctl_sched_base_slice.
1065 */
1066 se->slice = sysctl_sched_base_slice;
1067
1068 /*
1069 * EEVDF: vd_i = ve_i + r_i / w_i
1070 */
1071 se->deadline = se->vruntime + calc_delta_fair(se->slice, se);
1072
1073 /*
1074 * The task has consumed its request, reschedule.
1075 */
1076 if (cfs_rq->nr_running > 1) {
1077 resched_curr(rq_of(cfs_rq));
1078 clear_buddies(cfs_rq, se);
1079 }
1080 }
1081
1082 #include "pelt.h"
1083 #ifdef CONFIG_SMP
1084
1085 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu);
1086 static unsigned long task_h_load(struct task_struct *p);
1087 static unsigned long capacity_of(int cpu);
1088
1089 /* Give new sched_entity start runnable values to heavy its load in infant time */
init_entity_runnable_average(struct sched_entity * se)1090 void init_entity_runnable_average(struct sched_entity *se)
1091 {
1092 struct sched_avg *sa = &se->avg;
1093
1094 memset(sa, 0, sizeof(*sa));
1095
1096 /*
1097 * Tasks are initialized with full load to be seen as heavy tasks until
1098 * they get a chance to stabilize to their real load level.
1099 * Group entities are initialized with zero load to reflect the fact that
1100 * nothing has been attached to the task group yet.
1101 */
1102 if (entity_is_task(se))
1103 sa->load_avg = scale_load_down(se->load.weight);
1104
1105 /* when this task enqueue'ed, it will contribute to its cfs_rq's load_avg */
1106 }
1107
1108 /*
1109 * With new tasks being created, their initial util_avgs are extrapolated
1110 * based on the cfs_rq's current util_avg:
1111 *
1112 * util_avg = cfs_rq->util_avg / (cfs_rq->load_avg + 1) * se.load.weight
1113 *
1114 * However, in many cases, the above util_avg does not give a desired
1115 * value. Moreover, the sum of the util_avgs may be divergent, such
1116 * as when the series is a harmonic series.
1117 *
1118 * To solve this problem, we also cap the util_avg of successive tasks to
1119 * only 1/2 of the left utilization budget:
1120 *
1121 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n
1122 *
1123 * where n denotes the nth task and cpu_scale the CPU capacity.
1124 *
1125 * For example, for a CPU with 1024 of capacity, a simplest series from
1126 * the beginning would be like:
1127 *
1128 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ...
1129 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ...
1130 *
1131 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap)
1132 * if util_avg > util_avg_cap.
1133 */
post_init_entity_util_avg(struct task_struct * p)1134 void post_init_entity_util_avg(struct task_struct *p)
1135 {
1136 struct sched_entity *se = &p->se;
1137 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1138 struct sched_avg *sa = &se->avg;
1139 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq)));
1140 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2;
1141
1142 if (p->sched_class != &fair_sched_class) {
1143 /*
1144 * For !fair tasks do:
1145 *
1146 update_cfs_rq_load_avg(now, cfs_rq);
1147 attach_entity_load_avg(cfs_rq, se);
1148 switched_from_fair(rq, p);
1149 *
1150 * such that the next switched_to_fair() has the
1151 * expected state.
1152 */
1153 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq);
1154 return;
1155 }
1156
1157 if (cap > 0) {
1158 if (cfs_rq->avg.util_avg != 0) {
1159 sa->util_avg = cfs_rq->avg.util_avg * se->load.weight;
1160 sa->util_avg /= (cfs_rq->avg.load_avg + 1);
1161
1162 if (sa->util_avg > cap)
1163 sa->util_avg = cap;
1164 } else {
1165 sa->util_avg = cap;
1166 }
1167 }
1168
1169 sa->runnable_avg = sa->util_avg;
1170 }
1171
1172 #else /* !CONFIG_SMP */
init_entity_runnable_average(struct sched_entity * se)1173 void init_entity_runnable_average(struct sched_entity *se)
1174 {
1175 }
post_init_entity_util_avg(struct task_struct * p)1176 void post_init_entity_util_avg(struct task_struct *p)
1177 {
1178 }
update_tg_load_avg(struct cfs_rq * cfs_rq)1179 static void update_tg_load_avg(struct cfs_rq *cfs_rq)
1180 {
1181 }
1182 #endif /* CONFIG_SMP */
1183
1184 /*
1185 * Update the current task's runtime statistics.
1186 */
update_curr(struct cfs_rq * cfs_rq)1187 static void update_curr(struct cfs_rq *cfs_rq)
1188 {
1189 struct sched_entity *curr = cfs_rq->curr;
1190 u64 now = rq_clock_task(rq_of(cfs_rq));
1191 u64 delta_exec;
1192
1193 if (unlikely(!curr))
1194 return;
1195
1196 delta_exec = now - curr->exec_start;
1197 if (unlikely((s64)delta_exec <= 0))
1198 return;
1199
1200 curr->exec_start = now;
1201
1202 if (schedstat_enabled()) {
1203 struct sched_statistics *stats;
1204
1205 stats = __schedstats_from_se(curr);
1206 __schedstat_set(stats->exec_max,
1207 max(delta_exec, stats->exec_max));
1208 }
1209
1210 curr->sum_exec_runtime += delta_exec;
1211 schedstat_add(cfs_rq->exec_clock, delta_exec);
1212
1213 curr->vruntime += calc_delta_fair(delta_exec, curr);
1214 update_deadline(cfs_rq, curr);
1215 update_min_vruntime(cfs_rq);
1216
1217 if (entity_is_task(curr)) {
1218 struct task_struct *curtask = task_of(curr);
1219
1220 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
1221 cgroup_account_cputime(curtask, delta_exec);
1222 account_group_exec_runtime(curtask, delta_exec);
1223 }
1224
1225 account_cfs_rq_runtime(cfs_rq, delta_exec);
1226 }
1227
update_curr_fair(struct rq * rq)1228 static void update_curr_fair(struct rq *rq)
1229 {
1230 update_curr(cfs_rq_of(&rq->curr->se));
1231 }
1232
1233 static inline void
update_stats_wait_start_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1234 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1235 {
1236 struct sched_statistics *stats;
1237 struct task_struct *p = NULL;
1238
1239 if (!schedstat_enabled())
1240 return;
1241
1242 stats = __schedstats_from_se(se);
1243
1244 if (entity_is_task(se))
1245 p = task_of(se);
1246
1247 __update_stats_wait_start(rq_of(cfs_rq), p, stats);
1248 }
1249
1250 static inline void
update_stats_wait_end_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1251 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1252 {
1253 struct sched_statistics *stats;
1254 struct task_struct *p = NULL;
1255
1256 if (!schedstat_enabled())
1257 return;
1258
1259 stats = __schedstats_from_se(se);
1260
1261 /*
1262 * When the sched_schedstat changes from 0 to 1, some sched se
1263 * maybe already in the runqueue, the se->statistics.wait_start
1264 * will be 0.So it will let the delta wrong. We need to avoid this
1265 * scenario.
1266 */
1267 if (unlikely(!schedstat_val(stats->wait_start)))
1268 return;
1269
1270 if (entity_is_task(se))
1271 p = task_of(se);
1272
1273 __update_stats_wait_end(rq_of(cfs_rq), p, stats);
1274 }
1275
1276 static inline void
update_stats_enqueue_sleeper_fair(struct cfs_rq * cfs_rq,struct sched_entity * se)1277 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se)
1278 {
1279 struct sched_statistics *stats;
1280 struct task_struct *tsk = NULL;
1281
1282 if (!schedstat_enabled())
1283 return;
1284
1285 stats = __schedstats_from_se(se);
1286
1287 if (entity_is_task(se))
1288 tsk = task_of(se);
1289
1290 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats);
1291 }
1292
1293 /*
1294 * Task is being enqueued - update stats:
1295 */
1296 static inline void
update_stats_enqueue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1297 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1298 {
1299 if (!schedstat_enabled())
1300 return;
1301
1302 /*
1303 * Are we enqueueing a waiting task? (for current tasks
1304 * a dequeue/enqueue event is a NOP)
1305 */
1306 if (se != cfs_rq->curr)
1307 update_stats_wait_start_fair(cfs_rq, se);
1308
1309 if (flags & ENQUEUE_WAKEUP)
1310 update_stats_enqueue_sleeper_fair(cfs_rq, se);
1311 }
1312
1313 static inline void
update_stats_dequeue_fair(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)1314 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1315 {
1316
1317 if (!schedstat_enabled())
1318 return;
1319
1320 /*
1321 * Mark the end of the wait period if dequeueing a
1322 * waiting task:
1323 */
1324 if (se != cfs_rq->curr)
1325 update_stats_wait_end_fair(cfs_rq, se);
1326
1327 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) {
1328 struct task_struct *tsk = task_of(se);
1329 unsigned int state;
1330
1331 /* XXX racy against TTWU */
1332 state = READ_ONCE(tsk->__state);
1333 if (state & TASK_INTERRUPTIBLE)
1334 __schedstat_set(tsk->stats.sleep_start,
1335 rq_clock(rq_of(cfs_rq)));
1336 if (state & TASK_UNINTERRUPTIBLE)
1337 __schedstat_set(tsk->stats.block_start,
1338 rq_clock(rq_of(cfs_rq)));
1339 }
1340 }
1341
1342 /*
1343 * We are picking a new current task - update its stats:
1344 */
1345 static inline void
update_stats_curr_start(struct cfs_rq * cfs_rq,struct sched_entity * se)1346 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
1347 {
1348 /*
1349 * We are starting a new run period:
1350 */
1351 se->exec_start = rq_clock_task(rq_of(cfs_rq));
1352 }
1353
1354 /**************************************************
1355 * Scheduling class queueing methods:
1356 */
1357
is_core_idle(int cpu)1358 static inline bool is_core_idle(int cpu)
1359 {
1360 #ifdef CONFIG_SCHED_SMT
1361 int sibling;
1362
1363 for_each_cpu(sibling, cpu_smt_mask(cpu)) {
1364 if (cpu == sibling)
1365 continue;
1366
1367 if (!idle_cpu(sibling))
1368 return false;
1369 }
1370 #endif
1371
1372 return true;
1373 }
1374
1375 #ifdef CONFIG_NUMA
1376 #define NUMA_IMBALANCE_MIN 2
1377
1378 static inline long
adjust_numa_imbalance(int imbalance,int dst_running,int imb_numa_nr)1379 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr)
1380 {
1381 /*
1382 * Allow a NUMA imbalance if busy CPUs is less than the maximum
1383 * threshold. Above this threshold, individual tasks may be contending
1384 * for both memory bandwidth and any shared HT resources. This is an
1385 * approximation as the number of running tasks may not be related to
1386 * the number of busy CPUs due to sched_setaffinity.
1387 */
1388 if (dst_running > imb_numa_nr)
1389 return imbalance;
1390
1391 /*
1392 * Allow a small imbalance based on a simple pair of communicating
1393 * tasks that remain local when the destination is lightly loaded.
1394 */
1395 if (imbalance <= NUMA_IMBALANCE_MIN)
1396 return 0;
1397
1398 return imbalance;
1399 }
1400 #endif /* CONFIG_NUMA */
1401
1402 #ifdef CONFIG_NUMA_BALANCING
1403 /*
1404 * Approximate time to scan a full NUMA task in ms. The task scan period is
1405 * calculated based on the tasks virtual memory size and
1406 * numa_balancing_scan_size.
1407 */
1408 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
1409 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
1410
1411 /* Portion of address space to scan in MB */
1412 unsigned int sysctl_numa_balancing_scan_size = 256;
1413
1414 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
1415 unsigned int sysctl_numa_balancing_scan_delay = 1000;
1416
1417 /* The page with hint page fault latency < threshold in ms is considered hot */
1418 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC;
1419
1420 struct numa_group {
1421 refcount_t refcount;
1422
1423 spinlock_t lock; /* nr_tasks, tasks */
1424 int nr_tasks;
1425 pid_t gid;
1426 int active_nodes;
1427
1428 struct rcu_head rcu;
1429 unsigned long total_faults;
1430 unsigned long max_faults_cpu;
1431 /*
1432 * faults[] array is split into two regions: faults_mem and faults_cpu.
1433 *
1434 * Faults_cpu is used to decide whether memory should move
1435 * towards the CPU. As a consequence, these stats are weighted
1436 * more by CPU use than by memory faults.
1437 */
1438 unsigned long faults[];
1439 };
1440
1441 /*
1442 * For functions that can be called in multiple contexts that permit reading
1443 * ->numa_group (see struct task_struct for locking rules).
1444 */
deref_task_numa_group(struct task_struct * p)1445 static struct numa_group *deref_task_numa_group(struct task_struct *p)
1446 {
1447 return rcu_dereference_check(p->numa_group, p == current ||
1448 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu)));
1449 }
1450
deref_curr_numa_group(struct task_struct * p)1451 static struct numa_group *deref_curr_numa_group(struct task_struct *p)
1452 {
1453 return rcu_dereference_protected(p->numa_group, p == current);
1454 }
1455
1456 static inline unsigned long group_faults_priv(struct numa_group *ng);
1457 static inline unsigned long group_faults_shared(struct numa_group *ng);
1458
task_nr_scan_windows(struct task_struct * p)1459 static unsigned int task_nr_scan_windows(struct task_struct *p)
1460 {
1461 unsigned long rss = 0;
1462 unsigned long nr_scan_pages;
1463
1464 /*
1465 * Calculations based on RSS as non-present and empty pages are skipped
1466 * by the PTE scanner and NUMA hinting faults should be trapped based
1467 * on resident pages
1468 */
1469 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
1470 rss = get_mm_rss(p->mm);
1471 if (!rss)
1472 rss = nr_scan_pages;
1473
1474 rss = round_up(rss, nr_scan_pages);
1475 return rss / nr_scan_pages;
1476 }
1477
1478 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
1479 #define MAX_SCAN_WINDOW 2560
1480
task_scan_min(struct task_struct * p)1481 static unsigned int task_scan_min(struct task_struct *p)
1482 {
1483 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size);
1484 unsigned int scan, floor;
1485 unsigned int windows = 1;
1486
1487 if (scan_size < MAX_SCAN_WINDOW)
1488 windows = MAX_SCAN_WINDOW / scan_size;
1489 floor = 1000 / windows;
1490
1491 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
1492 return max_t(unsigned int, floor, scan);
1493 }
1494
task_scan_start(struct task_struct * p)1495 static unsigned int task_scan_start(struct task_struct *p)
1496 {
1497 unsigned long smin = task_scan_min(p);
1498 unsigned long period = smin;
1499 struct numa_group *ng;
1500
1501 /* Scale the maximum scan period with the amount of shared memory. */
1502 rcu_read_lock();
1503 ng = rcu_dereference(p->numa_group);
1504 if (ng) {
1505 unsigned long shared = group_faults_shared(ng);
1506 unsigned long private = group_faults_priv(ng);
1507
1508 period *= refcount_read(&ng->refcount);
1509 period *= shared + 1;
1510 period /= private + shared + 1;
1511 }
1512 rcu_read_unlock();
1513
1514 return max(smin, period);
1515 }
1516
task_scan_max(struct task_struct * p)1517 static unsigned int task_scan_max(struct task_struct *p)
1518 {
1519 unsigned long smin = task_scan_min(p);
1520 unsigned long smax;
1521 struct numa_group *ng;
1522
1523 /* Watch for min being lower than max due to floor calculations */
1524 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
1525
1526 /* Scale the maximum scan period with the amount of shared memory. */
1527 ng = deref_curr_numa_group(p);
1528 if (ng) {
1529 unsigned long shared = group_faults_shared(ng);
1530 unsigned long private = group_faults_priv(ng);
1531 unsigned long period = smax;
1532
1533 period *= refcount_read(&ng->refcount);
1534 period *= shared + 1;
1535 period /= private + shared + 1;
1536
1537 smax = max(smax, period);
1538 }
1539
1540 return max(smin, smax);
1541 }
1542
account_numa_enqueue(struct rq * rq,struct task_struct * p)1543 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
1544 {
1545 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE);
1546 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
1547 }
1548
account_numa_dequeue(struct rq * rq,struct task_struct * p)1549 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
1550 {
1551 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE);
1552 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
1553 }
1554
1555 /* Shared or private faults. */
1556 #define NR_NUMA_HINT_FAULT_TYPES 2
1557
1558 /* Memory and CPU locality */
1559 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
1560
1561 /* Averaged statistics, and temporary buffers. */
1562 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
1563
task_numa_group_id(struct task_struct * p)1564 pid_t task_numa_group_id(struct task_struct *p)
1565 {
1566 struct numa_group *ng;
1567 pid_t gid = 0;
1568
1569 rcu_read_lock();
1570 ng = rcu_dereference(p->numa_group);
1571 if (ng)
1572 gid = ng->gid;
1573 rcu_read_unlock();
1574
1575 return gid;
1576 }
1577
1578 /*
1579 * The averaged statistics, shared & private, memory & CPU,
1580 * occupy the first half of the array. The second half of the
1581 * array is for current counters, which are averaged into the
1582 * first set by task_numa_placement.
1583 */
task_faults_idx(enum numa_faults_stats s,int nid,int priv)1584 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
1585 {
1586 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
1587 }
1588
task_faults(struct task_struct * p,int nid)1589 static inline unsigned long task_faults(struct task_struct *p, int nid)
1590 {
1591 if (!p->numa_faults)
1592 return 0;
1593
1594 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1595 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
1596 }
1597
group_faults(struct task_struct * p,int nid)1598 static inline unsigned long group_faults(struct task_struct *p, int nid)
1599 {
1600 struct numa_group *ng = deref_task_numa_group(p);
1601
1602 if (!ng)
1603 return 0;
1604
1605 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
1606 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)];
1607 }
1608
group_faults_cpu(struct numa_group * group,int nid)1609 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
1610 {
1611 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] +
1612 group->faults[task_faults_idx(NUMA_CPU, nid, 1)];
1613 }
1614
group_faults_priv(struct numa_group * ng)1615 static inline unsigned long group_faults_priv(struct numa_group *ng)
1616 {
1617 unsigned long faults = 0;
1618 int node;
1619
1620 for_each_online_node(node) {
1621 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
1622 }
1623
1624 return faults;
1625 }
1626
group_faults_shared(struct numa_group * ng)1627 static inline unsigned long group_faults_shared(struct numa_group *ng)
1628 {
1629 unsigned long faults = 0;
1630 int node;
1631
1632 for_each_online_node(node) {
1633 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)];
1634 }
1635
1636 return faults;
1637 }
1638
1639 /*
1640 * A node triggering more than 1/3 as many NUMA faults as the maximum is
1641 * considered part of a numa group's pseudo-interleaving set. Migrations
1642 * between these nodes are slowed down, to allow things to settle down.
1643 */
1644 #define ACTIVE_NODE_FRACTION 3
1645
numa_is_active_node(int nid,struct numa_group * ng)1646 static bool numa_is_active_node(int nid, struct numa_group *ng)
1647 {
1648 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu;
1649 }
1650
1651 /* 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)1652 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
1653 int lim_dist, bool task)
1654 {
1655 unsigned long score = 0;
1656 int node, max_dist;
1657
1658 /*
1659 * All nodes are directly connected, and the same distance
1660 * from each other. No need for fancy placement algorithms.
1661 */
1662 if (sched_numa_topology_type == NUMA_DIRECT)
1663 return 0;
1664
1665 /* sched_max_numa_distance may be changed in parallel. */
1666 max_dist = READ_ONCE(sched_max_numa_distance);
1667 /*
1668 * This code is called for each node, introducing N^2 complexity,
1669 * which should be ok given the number of nodes rarely exceeds 8.
1670 */
1671 for_each_online_node(node) {
1672 unsigned long faults;
1673 int dist = node_distance(nid, node);
1674
1675 /*
1676 * The furthest away nodes in the system are not interesting
1677 * for placement; nid was already counted.
1678 */
1679 if (dist >= max_dist || node == nid)
1680 continue;
1681
1682 /*
1683 * On systems with a backplane NUMA topology, compare groups
1684 * of nodes, and move tasks towards the group with the most
1685 * memory accesses. When comparing two nodes at distance
1686 * "hoplimit", only nodes closer by than "hoplimit" are part
1687 * of each group. Skip other nodes.
1688 */
1689 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist)
1690 continue;
1691
1692 /* Add up the faults from nearby nodes. */
1693 if (task)
1694 faults = task_faults(p, node);
1695 else
1696 faults = group_faults(p, node);
1697
1698 /*
1699 * On systems with a glueless mesh NUMA topology, there are
1700 * no fixed "groups of nodes". Instead, nodes that are not
1701 * directly connected bounce traffic through intermediate
1702 * nodes; a numa_group can occupy any set of nodes.
1703 * The further away a node is, the less the faults count.
1704 * This seems to result in good task placement.
1705 */
1706 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1707 faults *= (max_dist - dist);
1708 faults /= (max_dist - LOCAL_DISTANCE);
1709 }
1710
1711 score += faults;
1712 }
1713
1714 return score;
1715 }
1716
1717 /*
1718 * These return the fraction of accesses done by a particular task, or
1719 * task group, on a particular numa node. The group weight is given a
1720 * larger multiplier, in order to group tasks together that are almost
1721 * evenly spread out between numa nodes.
1722 */
task_weight(struct task_struct * p,int nid,int dist)1723 static inline unsigned long task_weight(struct task_struct *p, int nid,
1724 int dist)
1725 {
1726 unsigned long faults, total_faults;
1727
1728 if (!p->numa_faults)
1729 return 0;
1730
1731 total_faults = p->total_numa_faults;
1732
1733 if (!total_faults)
1734 return 0;
1735
1736 faults = task_faults(p, nid);
1737 faults += score_nearby_nodes(p, nid, dist, true);
1738
1739 return 1000 * faults / total_faults;
1740 }
1741
group_weight(struct task_struct * p,int nid,int dist)1742 static inline unsigned long group_weight(struct task_struct *p, int nid,
1743 int dist)
1744 {
1745 struct numa_group *ng = deref_task_numa_group(p);
1746 unsigned long faults, total_faults;
1747
1748 if (!ng)
1749 return 0;
1750
1751 total_faults = ng->total_faults;
1752
1753 if (!total_faults)
1754 return 0;
1755
1756 faults = group_faults(p, nid);
1757 faults += score_nearby_nodes(p, nid, dist, false);
1758
1759 return 1000 * faults / total_faults;
1760 }
1761
1762 /*
1763 * If memory tiering mode is enabled, cpupid of slow memory page is
1764 * used to record scan time instead of CPU and PID. When tiering mode
1765 * is disabled at run time, the scan time (in cpupid) will be
1766 * interpreted as CPU and PID. So CPU needs to be checked to avoid to
1767 * access out of array bound.
1768 */
cpupid_valid(int cpupid)1769 static inline bool cpupid_valid(int cpupid)
1770 {
1771 return cpupid_to_cpu(cpupid) < nr_cpu_ids;
1772 }
1773
1774 /*
1775 * For memory tiering mode, if there are enough free pages (more than
1776 * enough watermark defined here) in fast memory node, to take full
1777 * advantage of fast memory capacity, all recently accessed slow
1778 * memory pages will be migrated to fast memory node without
1779 * considering hot threshold.
1780 */
pgdat_free_space_enough(struct pglist_data * pgdat)1781 static bool pgdat_free_space_enough(struct pglist_data *pgdat)
1782 {
1783 int z;
1784 unsigned long enough_wmark;
1785
1786 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT,
1787 pgdat->node_present_pages >> 4);
1788 for (z = pgdat->nr_zones - 1; z >= 0; z--) {
1789 struct zone *zone = pgdat->node_zones + z;
1790
1791 if (!populated_zone(zone))
1792 continue;
1793
1794 if (zone_watermark_ok(zone, 0,
1795 wmark_pages(zone, WMARK_PROMO) + enough_wmark,
1796 ZONE_MOVABLE, 0))
1797 return true;
1798 }
1799 return false;
1800 }
1801
1802 /*
1803 * For memory tiering mode, when page tables are scanned, the scan
1804 * time will be recorded in struct page in addition to make page
1805 * PROT_NONE for slow memory page. So when the page is accessed, in
1806 * hint page fault handler, the hint page fault latency is calculated
1807 * via,
1808 *
1809 * hint page fault latency = hint page fault time - scan time
1810 *
1811 * The smaller the hint page fault latency, the higher the possibility
1812 * for the page to be hot.
1813 */
numa_hint_fault_latency(struct page * page)1814 static int numa_hint_fault_latency(struct page *page)
1815 {
1816 int last_time, time;
1817
1818 time = jiffies_to_msecs(jiffies);
1819 last_time = xchg_page_access_time(page, time);
1820
1821 return (time - last_time) & PAGE_ACCESS_TIME_MASK;
1822 }
1823
1824 /*
1825 * For memory tiering mode, too high promotion/demotion throughput may
1826 * hurt application latency. So we provide a mechanism to rate limit
1827 * the number of pages that are tried to be promoted.
1828 */
numa_promotion_rate_limit(struct pglist_data * pgdat,unsigned long rate_limit,int nr)1829 static bool numa_promotion_rate_limit(struct pglist_data *pgdat,
1830 unsigned long rate_limit, int nr)
1831 {
1832 unsigned long nr_cand;
1833 unsigned int now, start;
1834
1835 now = jiffies_to_msecs(jiffies);
1836 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr);
1837 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1838 start = pgdat->nbp_rl_start;
1839 if (now - start > MSEC_PER_SEC &&
1840 cmpxchg(&pgdat->nbp_rl_start, start, now) == start)
1841 pgdat->nbp_rl_nr_cand = nr_cand;
1842 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit)
1843 return true;
1844 return false;
1845 }
1846
1847 #define NUMA_MIGRATION_ADJUST_STEPS 16
1848
numa_promotion_adjust_threshold(struct pglist_data * pgdat,unsigned long rate_limit,unsigned int ref_th)1849 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat,
1850 unsigned long rate_limit,
1851 unsigned int ref_th)
1852 {
1853 unsigned int now, start, th_period, unit_th, th;
1854 unsigned long nr_cand, ref_cand, diff_cand;
1855
1856 now = jiffies_to_msecs(jiffies);
1857 th_period = sysctl_numa_balancing_scan_period_max;
1858 start = pgdat->nbp_th_start;
1859 if (now - start > th_period &&
1860 cmpxchg(&pgdat->nbp_th_start, start, now) == start) {
1861 ref_cand = rate_limit *
1862 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC;
1863 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE);
1864 diff_cand = nr_cand - pgdat->nbp_th_nr_cand;
1865 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS;
1866 th = pgdat->nbp_threshold ? : ref_th;
1867 if (diff_cand > ref_cand * 11 / 10)
1868 th = max(th - unit_th, unit_th);
1869 else if (diff_cand < ref_cand * 9 / 10)
1870 th = min(th + unit_th, ref_th * 2);
1871 pgdat->nbp_th_nr_cand = nr_cand;
1872 pgdat->nbp_threshold = th;
1873 }
1874 }
1875
should_numa_migrate_memory(struct task_struct * p,struct page * page,int src_nid,int dst_cpu)1876 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1877 int src_nid, int dst_cpu)
1878 {
1879 struct numa_group *ng = deref_curr_numa_group(p);
1880 int dst_nid = cpu_to_node(dst_cpu);
1881 int last_cpupid, this_cpupid;
1882
1883 /*
1884 * The pages in slow memory node should be migrated according
1885 * to hot/cold instead of private/shared.
1886 */
1887 if (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING &&
1888 !node_is_toptier(src_nid)) {
1889 struct pglist_data *pgdat;
1890 unsigned long rate_limit;
1891 unsigned int latency, th, def_th;
1892
1893 pgdat = NODE_DATA(dst_nid);
1894 if (pgdat_free_space_enough(pgdat)) {
1895 /* workload changed, reset hot threshold */
1896 pgdat->nbp_threshold = 0;
1897 return true;
1898 }
1899
1900 def_th = sysctl_numa_balancing_hot_threshold;
1901 rate_limit = sysctl_numa_balancing_promote_rate_limit << \
1902 (20 - PAGE_SHIFT);
1903 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th);
1904
1905 th = pgdat->nbp_threshold ? : def_th;
1906 latency = numa_hint_fault_latency(page);
1907 if (latency >= th)
1908 return false;
1909
1910 return !numa_promotion_rate_limit(pgdat, rate_limit,
1911 thp_nr_pages(page));
1912 }
1913
1914 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1915 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1916
1917 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) &&
1918 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid))
1919 return false;
1920
1921 /*
1922 * Allow first faults or private faults to migrate immediately early in
1923 * the lifetime of a task. The magic number 4 is based on waiting for
1924 * two full passes of the "multi-stage node selection" test that is
1925 * executed below.
1926 */
1927 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) &&
1928 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid)))
1929 return true;
1930
1931 /*
1932 * Multi-stage node selection is used in conjunction with a periodic
1933 * migration fault to build a temporal task<->page relation. By using
1934 * a two-stage filter we remove short/unlikely relations.
1935 *
1936 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1937 * a task's usage of a particular page (n_p) per total usage of this
1938 * page (n_t) (in a given time-span) to a probability.
1939 *
1940 * Our periodic faults will sample this probability and getting the
1941 * same result twice in a row, given these samples are fully
1942 * independent, is then given by P(n)^2, provided our sample period
1943 * is sufficiently short compared to the usage pattern.
1944 *
1945 * This quadric squishes small probabilities, making it less likely we
1946 * act on an unlikely task<->page relation.
1947 */
1948 if (!cpupid_pid_unset(last_cpupid) &&
1949 cpupid_to_nid(last_cpupid) != dst_nid)
1950 return false;
1951
1952 /* Always allow migrate on private faults */
1953 if (cpupid_match_pid(p, last_cpupid))
1954 return true;
1955
1956 /* A shared fault, but p->numa_group has not been set up yet. */
1957 if (!ng)
1958 return true;
1959
1960 /*
1961 * Destination node is much more heavily used than the source
1962 * node? Allow migration.
1963 */
1964 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) *
1965 ACTIVE_NODE_FRACTION)
1966 return true;
1967
1968 /*
1969 * Distribute memory according to CPU & memory use on each node,
1970 * with 3/4 hysteresis to avoid unnecessary memory migrations:
1971 *
1972 * faults_cpu(dst) 3 faults_cpu(src)
1973 * --------------- * - > ---------------
1974 * faults_mem(dst) 4 faults_mem(src)
1975 */
1976 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 >
1977 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4;
1978 }
1979
1980 /*
1981 * 'numa_type' describes the node at the moment of load balancing.
1982 */
1983 enum numa_type {
1984 /* The node has spare capacity that can be used to run more tasks. */
1985 node_has_spare = 0,
1986 /*
1987 * The node is fully used and the tasks don't compete for more CPU
1988 * cycles. Nevertheless, some tasks might wait before running.
1989 */
1990 node_fully_busy,
1991 /*
1992 * The node is overloaded and can't provide expected CPU cycles to all
1993 * tasks.
1994 */
1995 node_overloaded
1996 };
1997
1998 /* Cached statistics for all CPUs within a node */
1999 struct numa_stats {
2000 unsigned long load;
2001 unsigned long runnable;
2002 unsigned long util;
2003 /* Total compute capacity of CPUs on a node */
2004 unsigned long compute_capacity;
2005 unsigned int nr_running;
2006 unsigned int weight;
2007 enum numa_type node_type;
2008 int idle_cpu;
2009 };
2010
2011 struct task_numa_env {
2012 struct task_struct *p;
2013
2014 int src_cpu, src_nid;
2015 int dst_cpu, dst_nid;
2016 int imb_numa_nr;
2017
2018 struct numa_stats src_stats, dst_stats;
2019
2020 int imbalance_pct;
2021 int dist;
2022
2023 struct task_struct *best_task;
2024 long best_imp;
2025 int best_cpu;
2026 };
2027
2028 static unsigned long cpu_load(struct rq *rq);
2029 static unsigned long cpu_runnable(struct rq *rq);
2030
2031 static inline enum
numa_classify(unsigned int imbalance_pct,struct numa_stats * ns)2032 numa_type numa_classify(unsigned int imbalance_pct,
2033 struct numa_stats *ns)
2034 {
2035 if ((ns->nr_running > ns->weight) &&
2036 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) ||
2037 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100))))
2038 return node_overloaded;
2039
2040 if ((ns->nr_running < ns->weight) ||
2041 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) &&
2042 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100))))
2043 return node_has_spare;
2044
2045 return node_fully_busy;
2046 }
2047
2048 #ifdef CONFIG_SCHED_SMT
2049 /* Forward declarations of select_idle_sibling helpers */
2050 static inline bool test_idle_cores(int cpu);
numa_idle_core(int idle_core,int cpu)2051 static inline int numa_idle_core(int idle_core, int cpu)
2052 {
2053 if (!static_branch_likely(&sched_smt_present) ||
2054 idle_core >= 0 || !test_idle_cores(cpu))
2055 return idle_core;
2056
2057 /*
2058 * Prefer cores instead of packing HT siblings
2059 * and triggering future load balancing.
2060 */
2061 if (is_core_idle(cpu))
2062 idle_core = cpu;
2063
2064 return idle_core;
2065 }
2066 #else
numa_idle_core(int idle_core,int cpu)2067 static inline int numa_idle_core(int idle_core, int cpu)
2068 {
2069 return idle_core;
2070 }
2071 #endif
2072
2073 /*
2074 * Gather all necessary information to make NUMA balancing placement
2075 * decisions that are compatible with standard load balancer. This
2076 * borrows code and logic from update_sg_lb_stats but sharing a
2077 * common implementation is impractical.
2078 */
update_numa_stats(struct task_numa_env * env,struct numa_stats * ns,int nid,bool find_idle)2079 static void update_numa_stats(struct task_numa_env *env,
2080 struct numa_stats *ns, int nid,
2081 bool find_idle)
2082 {
2083 int cpu, idle_core = -1;
2084
2085 memset(ns, 0, sizeof(*ns));
2086 ns->idle_cpu = -1;
2087
2088 rcu_read_lock();
2089 for_each_cpu(cpu, cpumask_of_node(nid)) {
2090 struct rq *rq = cpu_rq(cpu);
2091
2092 ns->load += cpu_load(rq);
2093 ns->runnable += cpu_runnable(rq);
2094 ns->util += cpu_util_cfs(cpu);
2095 ns->nr_running += rq->cfs.h_nr_running;
2096 ns->compute_capacity += capacity_of(cpu);
2097
2098 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) {
2099 if (READ_ONCE(rq->numa_migrate_on) ||
2100 !cpumask_test_cpu(cpu, env->p->cpus_ptr))
2101 continue;
2102
2103 if (ns->idle_cpu == -1)
2104 ns->idle_cpu = cpu;
2105
2106 idle_core = numa_idle_core(idle_core, cpu);
2107 }
2108 }
2109 rcu_read_unlock();
2110
2111 ns->weight = cpumask_weight(cpumask_of_node(nid));
2112
2113 ns->node_type = numa_classify(env->imbalance_pct, ns);
2114
2115 if (idle_core >= 0)
2116 ns->idle_cpu = idle_core;
2117 }
2118
task_numa_assign(struct task_numa_env * env,struct task_struct * p,long imp)2119 static void task_numa_assign(struct task_numa_env *env,
2120 struct task_struct *p, long imp)
2121 {
2122 struct rq *rq = cpu_rq(env->dst_cpu);
2123
2124 /* Check if run-queue part of active NUMA balance. */
2125 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) {
2126 int cpu;
2127 int start = env->dst_cpu;
2128
2129 /* Find alternative idle CPU. */
2130 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) {
2131 if (cpu == env->best_cpu || !idle_cpu(cpu) ||
2132 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) {
2133 continue;
2134 }
2135
2136 env->dst_cpu = cpu;
2137 rq = cpu_rq(env->dst_cpu);
2138 if (!xchg(&rq->numa_migrate_on, 1))
2139 goto assign;
2140 }
2141
2142 /* Failed to find an alternative idle CPU */
2143 return;
2144 }
2145
2146 assign:
2147 /*
2148 * Clear previous best_cpu/rq numa-migrate flag, since task now
2149 * found a better CPU to move/swap.
2150 */
2151 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) {
2152 rq = cpu_rq(env->best_cpu);
2153 WRITE_ONCE(rq->numa_migrate_on, 0);
2154 }
2155
2156 if (env->best_task)
2157 put_task_struct(env->best_task);
2158 if (p)
2159 get_task_struct(p);
2160
2161 env->best_task = p;
2162 env->best_imp = imp;
2163 env->best_cpu = env->dst_cpu;
2164 }
2165
load_too_imbalanced(long src_load,long dst_load,struct task_numa_env * env)2166 static bool load_too_imbalanced(long src_load, long dst_load,
2167 struct task_numa_env *env)
2168 {
2169 long imb, old_imb;
2170 long orig_src_load, orig_dst_load;
2171 long src_capacity, dst_capacity;
2172
2173 /*
2174 * The load is corrected for the CPU capacity available on each node.
2175 *
2176 * src_load dst_load
2177 * ------------ vs ---------
2178 * src_capacity dst_capacity
2179 */
2180 src_capacity = env->src_stats.compute_capacity;
2181 dst_capacity = env->dst_stats.compute_capacity;
2182
2183 imb = abs(dst_load * src_capacity - src_load * dst_capacity);
2184
2185 orig_src_load = env->src_stats.load;
2186 orig_dst_load = env->dst_stats.load;
2187
2188 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity);
2189
2190 /* Would this change make things worse? */
2191 return (imb > old_imb);
2192 }
2193
2194 /*
2195 * Maximum NUMA importance can be 1998 (2*999);
2196 * SMALLIMP @ 30 would be close to 1998/64.
2197 * Used to deter task migration.
2198 */
2199 #define SMALLIMP 30
2200
2201 /*
2202 * This checks if the overall compute and NUMA accesses of the system would
2203 * be improved if the source tasks was migrated to the target dst_cpu taking
2204 * into account that it might be best if task running on the dst_cpu should
2205 * be exchanged with the source task
2206 */
task_numa_compare(struct task_numa_env * env,long taskimp,long groupimp,bool maymove)2207 static bool task_numa_compare(struct task_numa_env *env,
2208 long taskimp, long groupimp, bool maymove)
2209 {
2210 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p);
2211 struct rq *dst_rq = cpu_rq(env->dst_cpu);
2212 long imp = p_ng ? groupimp : taskimp;
2213 struct task_struct *cur;
2214 long src_load, dst_load;
2215 int dist = env->dist;
2216 long moveimp = imp;
2217 long load;
2218 bool stopsearch = false;
2219
2220 if (READ_ONCE(dst_rq->numa_migrate_on))
2221 return false;
2222
2223 rcu_read_lock();
2224 cur = rcu_dereference(dst_rq->curr);
2225 if (cur && ((cur->flags & PF_EXITING) || is_idle_task(cur)))
2226 cur = NULL;
2227
2228 /*
2229 * Because we have preemption enabled we can get migrated around and
2230 * end try selecting ourselves (current == env->p) as a swap candidate.
2231 */
2232 if (cur == env->p) {
2233 stopsearch = true;
2234 goto unlock;
2235 }
2236
2237 if (!cur) {
2238 if (maymove && moveimp >= env->best_imp)
2239 goto assign;
2240 else
2241 goto unlock;
2242 }
2243
2244 /* Skip this swap candidate if cannot move to the source cpu. */
2245 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr))
2246 goto unlock;
2247
2248 /*
2249 * Skip this swap candidate if it is not moving to its preferred
2250 * node and the best task is.
2251 */
2252 if (env->best_task &&
2253 env->best_task->numa_preferred_nid == env->src_nid &&
2254 cur->numa_preferred_nid != env->src_nid) {
2255 goto unlock;
2256 }
2257
2258 /*
2259 * "imp" is the fault differential for the source task between the
2260 * source and destination node. Calculate the total differential for
2261 * the source task and potential destination task. The more negative
2262 * the value is, the more remote accesses that would be expected to
2263 * be incurred if the tasks were swapped.
2264 *
2265 * If dst and source tasks are in the same NUMA group, or not
2266 * in any group then look only at task weights.
2267 */
2268 cur_ng = rcu_dereference(cur->numa_group);
2269 if (cur_ng == p_ng) {
2270 /*
2271 * Do not swap within a group or between tasks that have
2272 * no group if there is spare capacity. Swapping does
2273 * not address the load imbalance and helps one task at
2274 * the cost of punishing another.
2275 */
2276 if (env->dst_stats.node_type == node_has_spare)
2277 goto unlock;
2278
2279 imp = taskimp + task_weight(cur, env->src_nid, dist) -
2280 task_weight(cur, env->dst_nid, dist);
2281 /*
2282 * Add some hysteresis to prevent swapping the
2283 * tasks within a group over tiny differences.
2284 */
2285 if (cur_ng)
2286 imp -= imp / 16;
2287 } else {
2288 /*
2289 * Compare the group weights. If a task is all by itself
2290 * (not part of a group), use the task weight instead.
2291 */
2292 if (cur_ng && p_ng)
2293 imp += group_weight(cur, env->src_nid, dist) -
2294 group_weight(cur, env->dst_nid, dist);
2295 else
2296 imp += task_weight(cur, env->src_nid, dist) -
2297 task_weight(cur, env->dst_nid, dist);
2298 }
2299
2300 /* Discourage picking a task already on its preferred node */
2301 if (cur->numa_preferred_nid == env->dst_nid)
2302 imp -= imp / 16;
2303
2304 /*
2305 * Encourage picking a task that moves to its preferred node.
2306 * This potentially makes imp larger than it's maximum of
2307 * 1998 (see SMALLIMP and task_weight for why) but in this
2308 * case, it does not matter.
2309 */
2310 if (cur->numa_preferred_nid == env->src_nid)
2311 imp += imp / 8;
2312
2313 if (maymove && moveimp > imp && moveimp > env->best_imp) {
2314 imp = moveimp;
2315 cur = NULL;
2316 goto assign;
2317 }
2318
2319 /*
2320 * Prefer swapping with a task moving to its preferred node over a
2321 * task that is not.
2322 */
2323 if (env->best_task && cur->numa_preferred_nid == env->src_nid &&
2324 env->best_task->numa_preferred_nid != env->src_nid) {
2325 goto assign;
2326 }
2327
2328 /*
2329 * If the NUMA importance is less than SMALLIMP,
2330 * task migration might only result in ping pong
2331 * of tasks and also hurt performance due to cache
2332 * misses.
2333 */
2334 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2)
2335 goto unlock;
2336
2337 /*
2338 * In the overloaded case, try and keep the load balanced.
2339 */
2340 load = task_h_load(env->p) - task_h_load(cur);
2341 if (!load)
2342 goto assign;
2343
2344 dst_load = env->dst_stats.load + load;
2345 src_load = env->src_stats.load - load;
2346
2347 if (load_too_imbalanced(src_load, dst_load, env))
2348 goto unlock;
2349
2350 assign:
2351 /* Evaluate an idle CPU for a task numa move. */
2352 if (!cur) {
2353 int cpu = env->dst_stats.idle_cpu;
2354
2355 /* Nothing cached so current CPU went idle since the search. */
2356 if (cpu < 0)
2357 cpu = env->dst_cpu;
2358
2359 /*
2360 * If the CPU is no longer truly idle and the previous best CPU
2361 * is, keep using it.
2362 */
2363 if (!idle_cpu(cpu) && env->best_cpu >= 0 &&
2364 idle_cpu(env->best_cpu)) {
2365 cpu = env->best_cpu;
2366 }
2367
2368 env->dst_cpu = cpu;
2369 }
2370
2371 task_numa_assign(env, cur, imp);
2372
2373 /*
2374 * If a move to idle is allowed because there is capacity or load
2375 * balance improves then stop the search. While a better swap
2376 * candidate may exist, a search is not free.
2377 */
2378 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu))
2379 stopsearch = true;
2380
2381 /*
2382 * If a swap candidate must be identified and the current best task
2383 * moves its preferred node then stop the search.
2384 */
2385 if (!maymove && env->best_task &&
2386 env->best_task->numa_preferred_nid == env->src_nid) {
2387 stopsearch = true;
2388 }
2389 unlock:
2390 rcu_read_unlock();
2391
2392 return stopsearch;
2393 }
2394
task_numa_find_cpu(struct task_numa_env * env,long taskimp,long groupimp)2395 static void task_numa_find_cpu(struct task_numa_env *env,
2396 long taskimp, long groupimp)
2397 {
2398 bool maymove = false;
2399 int cpu;
2400
2401 /*
2402 * If dst node has spare capacity, then check if there is an
2403 * imbalance that would be overruled by the load balancer.
2404 */
2405 if (env->dst_stats.node_type == node_has_spare) {
2406 unsigned int imbalance;
2407 int src_running, dst_running;
2408
2409 /*
2410 * Would movement cause an imbalance? Note that if src has
2411 * more running tasks that the imbalance is ignored as the
2412 * move improves the imbalance from the perspective of the
2413 * CPU load balancer.
2414 * */
2415 src_running = env->src_stats.nr_running - 1;
2416 dst_running = env->dst_stats.nr_running + 1;
2417 imbalance = max(0, dst_running - src_running);
2418 imbalance = adjust_numa_imbalance(imbalance, dst_running,
2419 env->imb_numa_nr);
2420
2421 /* Use idle CPU if there is no imbalance */
2422 if (!imbalance) {
2423 maymove = true;
2424 if (env->dst_stats.idle_cpu >= 0) {
2425 env->dst_cpu = env->dst_stats.idle_cpu;
2426 task_numa_assign(env, NULL, 0);
2427 return;
2428 }
2429 }
2430 } else {
2431 long src_load, dst_load, load;
2432 /*
2433 * If the improvement from just moving env->p direction is better
2434 * than swapping tasks around, check if a move is possible.
2435 */
2436 load = task_h_load(env->p);
2437 dst_load = env->dst_stats.load + load;
2438 src_load = env->src_stats.load - load;
2439 maymove = !load_too_imbalanced(src_load, dst_load, env);
2440 }
2441
2442 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
2443 /* Skip this CPU if the source task cannot migrate */
2444 if (!cpumask_test_cpu(cpu, env->p->cpus_ptr))
2445 continue;
2446
2447 env->dst_cpu = cpu;
2448 if (task_numa_compare(env, taskimp, groupimp, maymove))
2449 break;
2450 }
2451 }
2452
task_numa_migrate(struct task_struct * p)2453 static int task_numa_migrate(struct task_struct *p)
2454 {
2455 struct task_numa_env env = {
2456 .p = p,
2457
2458 .src_cpu = task_cpu(p),
2459 .src_nid = task_node(p),
2460
2461 .imbalance_pct = 112,
2462
2463 .best_task = NULL,
2464 .best_imp = 0,
2465 .best_cpu = -1,
2466 };
2467 unsigned long taskweight, groupweight;
2468 struct sched_domain *sd;
2469 long taskimp, groupimp;
2470 struct numa_group *ng;
2471 struct rq *best_rq;
2472 int nid, ret, dist;
2473
2474 /*
2475 * Pick the lowest SD_NUMA domain, as that would have the smallest
2476 * imbalance and would be the first to start moving tasks about.
2477 *
2478 * And we want to avoid any moving of tasks about, as that would create
2479 * random movement of tasks -- counter the numa conditions we're trying
2480 * to satisfy here.
2481 */
2482 rcu_read_lock();
2483 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
2484 if (sd) {
2485 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
2486 env.imb_numa_nr = sd->imb_numa_nr;
2487 }
2488 rcu_read_unlock();
2489
2490 /*
2491 * Cpusets can break the scheduler domain tree into smaller
2492 * balance domains, some of which do not cross NUMA boundaries.
2493 * Tasks that are "trapped" in such domains cannot be migrated
2494 * elsewhere, so there is no point in (re)trying.
2495 */
2496 if (unlikely(!sd)) {
2497 sched_setnuma(p, task_node(p));
2498 return -EINVAL;
2499 }
2500
2501 env.dst_nid = p->numa_preferred_nid;
2502 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
2503 taskweight = task_weight(p, env.src_nid, dist);
2504 groupweight = group_weight(p, env.src_nid, dist);
2505 update_numa_stats(&env, &env.src_stats, env.src_nid, false);
2506 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
2507 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
2508 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2509
2510 /* Try to find a spot on the preferred nid. */
2511 task_numa_find_cpu(&env, taskimp, groupimp);
2512
2513 /*
2514 * Look at other nodes in these cases:
2515 * - there is no space available on the preferred_nid
2516 * - the task is part of a numa_group that is interleaved across
2517 * multiple NUMA nodes; in order to better consolidate the group,
2518 * we need to check other locations.
2519 */
2520 ng = deref_curr_numa_group(p);
2521 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) {
2522 for_each_node_state(nid, N_CPU) {
2523 if (nid == env.src_nid || nid == p->numa_preferred_nid)
2524 continue;
2525
2526 dist = node_distance(env.src_nid, env.dst_nid);
2527 if (sched_numa_topology_type == NUMA_BACKPLANE &&
2528 dist != env.dist) {
2529 taskweight = task_weight(p, env.src_nid, dist);
2530 groupweight = group_weight(p, env.src_nid, dist);
2531 }
2532
2533 /* Only consider nodes where both task and groups benefit */
2534 taskimp = task_weight(p, nid, dist) - taskweight;
2535 groupimp = group_weight(p, nid, dist) - groupweight;
2536 if (taskimp < 0 && groupimp < 0)
2537 continue;
2538
2539 env.dist = dist;
2540 env.dst_nid = nid;
2541 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true);
2542 task_numa_find_cpu(&env, taskimp, groupimp);
2543 }
2544 }
2545
2546 /*
2547 * If the task is part of a workload that spans multiple NUMA nodes,
2548 * and is migrating into one of the workload's active nodes, remember
2549 * this node as the task's preferred numa node, so the workload can
2550 * settle down.
2551 * A task that migrated to a second choice node will be better off
2552 * trying for a better one later. Do not set the preferred node here.
2553 */
2554 if (ng) {
2555 if (env.best_cpu == -1)
2556 nid = env.src_nid;
2557 else
2558 nid = cpu_to_node(env.best_cpu);
2559
2560 if (nid != p->numa_preferred_nid)
2561 sched_setnuma(p, nid);
2562 }
2563
2564 /* No better CPU than the current one was found. */
2565 if (env.best_cpu == -1) {
2566 trace_sched_stick_numa(p, env.src_cpu, NULL, -1);
2567 return -EAGAIN;
2568 }
2569
2570 best_rq = cpu_rq(env.best_cpu);
2571 if (env.best_task == NULL) {
2572 ret = migrate_task_to(p, env.best_cpu);
2573 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2574 if (ret != 0)
2575 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu);
2576 return ret;
2577 }
2578
2579 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu);
2580 WRITE_ONCE(best_rq->numa_migrate_on, 0);
2581
2582 if (ret != 0)
2583 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu);
2584 put_task_struct(env.best_task);
2585 return ret;
2586 }
2587
2588 /* Attempt to migrate a task to a CPU on the preferred node. */
numa_migrate_preferred(struct task_struct * p)2589 static void numa_migrate_preferred(struct task_struct *p)
2590 {
2591 unsigned long interval = HZ;
2592
2593 /* This task has no NUMA fault statistics yet */
2594 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults))
2595 return;
2596
2597 /* Periodically retry migrating the task to the preferred node */
2598 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
2599 p->numa_migrate_retry = jiffies + interval;
2600
2601 /* Success if task is already running on preferred CPU */
2602 if (task_node(p) == p->numa_preferred_nid)
2603 return;
2604
2605 /* Otherwise, try migrate to a CPU on the preferred node */
2606 task_numa_migrate(p);
2607 }
2608
2609 /*
2610 * Find out how many nodes the workload is actively running on. Do this by
2611 * tracking the nodes from which NUMA hinting faults are triggered. This can
2612 * be different from the set of nodes where the workload's memory is currently
2613 * located.
2614 */
numa_group_count_active_nodes(struct numa_group * numa_group)2615 static void numa_group_count_active_nodes(struct numa_group *numa_group)
2616 {
2617 unsigned long faults, max_faults = 0;
2618 int nid, active_nodes = 0;
2619
2620 for_each_node_state(nid, N_CPU) {
2621 faults = group_faults_cpu(numa_group, nid);
2622 if (faults > max_faults)
2623 max_faults = faults;
2624 }
2625
2626 for_each_node_state(nid, N_CPU) {
2627 faults = group_faults_cpu(numa_group, nid);
2628 if (faults * ACTIVE_NODE_FRACTION > max_faults)
2629 active_nodes++;
2630 }
2631
2632 numa_group->max_faults_cpu = max_faults;
2633 numa_group->active_nodes = active_nodes;
2634 }
2635
2636 /*
2637 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
2638 * increments. The more local the fault statistics are, the higher the scan
2639 * period will be for the next scan window. If local/(local+remote) ratio is
2640 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
2641 * the scan period will decrease. Aim for 70% local accesses.
2642 */
2643 #define NUMA_PERIOD_SLOTS 10
2644 #define NUMA_PERIOD_THRESHOLD 7
2645
2646 /*
2647 * Increase the scan period (slow down scanning) if the majority of
2648 * our memory is already on our local node, or if the majority of
2649 * the page accesses are shared with other processes.
2650 * Otherwise, decrease the scan period.
2651 */
update_task_scan_period(struct task_struct * p,unsigned long shared,unsigned long private)2652 static void update_task_scan_period(struct task_struct *p,
2653 unsigned long shared, unsigned long private)
2654 {
2655 unsigned int period_slot;
2656 int lr_ratio, ps_ratio;
2657 int diff;
2658
2659 unsigned long remote = p->numa_faults_locality[0];
2660 unsigned long local = p->numa_faults_locality[1];
2661
2662 /*
2663 * If there were no record hinting faults then either the task is
2664 * completely idle or all activity is in areas that are not of interest
2665 * to automatic numa balancing. Related to that, if there were failed
2666 * migration then it implies we are migrating too quickly or the local
2667 * node is overloaded. In either case, scan slower
2668 */
2669 if (local + shared == 0 || p->numa_faults_locality[2]) {
2670 p->numa_scan_period = min(p->numa_scan_period_max,
2671 p->numa_scan_period << 1);
2672
2673 p->mm->numa_next_scan = jiffies +
2674 msecs_to_jiffies(p->numa_scan_period);
2675
2676 return;
2677 }
2678
2679 /*
2680 * Prepare to scale scan period relative to the current period.
2681 * == NUMA_PERIOD_THRESHOLD scan period stays the same
2682 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
2683 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
2684 */
2685 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
2686 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
2687 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared);
2688
2689 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) {
2690 /*
2691 * Most memory accesses are local. There is no need to
2692 * do fast NUMA scanning, since memory is already local.
2693 */
2694 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD;
2695 if (!slot)
2696 slot = 1;
2697 diff = slot * period_slot;
2698 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) {
2699 /*
2700 * Most memory accesses are shared with other tasks.
2701 * There is no point in continuing fast NUMA scanning,
2702 * since other tasks may just move the memory elsewhere.
2703 */
2704 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD;
2705 if (!slot)
2706 slot = 1;
2707 diff = slot * period_slot;
2708 } else {
2709 /*
2710 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS,
2711 * yet they are not on the local NUMA node. Speed up
2712 * NUMA scanning to get the memory moved over.
2713 */
2714 int ratio = max(lr_ratio, ps_ratio);
2715 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
2716 }
2717
2718 p->numa_scan_period = clamp(p->numa_scan_period + diff,
2719 task_scan_min(p), task_scan_max(p));
2720 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2721 }
2722
2723 /*
2724 * Get the fraction of time the task has been running since the last
2725 * NUMA placement cycle. The scheduler keeps similar statistics, but
2726 * decays those on a 32ms period, which is orders of magnitude off
2727 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
2728 * stats only if the task is so new there are no NUMA statistics yet.
2729 */
numa_get_avg_runtime(struct task_struct * p,u64 * period)2730 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
2731 {
2732 u64 runtime, delta, now;
2733 /* Use the start of this time slice to avoid calculations. */
2734 now = p->se.exec_start;
2735 runtime = p->se.sum_exec_runtime;
2736
2737 if (p->last_task_numa_placement) {
2738 delta = runtime - p->last_sum_exec_runtime;
2739 *period = now - p->last_task_numa_placement;
2740
2741 /* Avoid time going backwards, prevent potential divide error: */
2742 if (unlikely((s64)*period < 0))
2743 *period = 0;
2744 } else {
2745 delta = p->se.avg.load_sum;
2746 *period = LOAD_AVG_MAX;
2747 }
2748
2749 p->last_sum_exec_runtime = runtime;
2750 p->last_task_numa_placement = now;
2751
2752 return delta;
2753 }
2754
2755 /*
2756 * Determine the preferred nid for a task in a numa_group. This needs to
2757 * be done in a way that produces consistent results with group_weight,
2758 * otherwise workloads might not converge.
2759 */
preferred_group_nid(struct task_struct * p,int nid)2760 static int preferred_group_nid(struct task_struct *p, int nid)
2761 {
2762 nodemask_t nodes;
2763 int dist;
2764
2765 /* Direct connections between all NUMA nodes. */
2766 if (sched_numa_topology_type == NUMA_DIRECT)
2767 return nid;
2768
2769 /*
2770 * On a system with glueless mesh NUMA topology, group_weight
2771 * scores nodes according to the number of NUMA hinting faults on
2772 * both the node itself, and on nearby nodes.
2773 */
2774 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
2775 unsigned long score, max_score = 0;
2776 int node, max_node = nid;
2777
2778 dist = sched_max_numa_distance;
2779
2780 for_each_node_state(node, N_CPU) {
2781 score = group_weight(p, node, dist);
2782 if (score > max_score) {
2783 max_score = score;
2784 max_node = node;
2785 }
2786 }
2787 return max_node;
2788 }
2789
2790 /*
2791 * Finding the preferred nid in a system with NUMA backplane
2792 * interconnect topology is more involved. The goal is to locate
2793 * tasks from numa_groups near each other in the system, and
2794 * untangle workloads from different sides of the system. This requires
2795 * searching down the hierarchy of node groups, recursively searching
2796 * inside the highest scoring group of nodes. The nodemask tricks
2797 * keep the complexity of the search down.
2798 */
2799 nodes = node_states[N_CPU];
2800 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
2801 unsigned long max_faults = 0;
2802 nodemask_t max_group = NODE_MASK_NONE;
2803 int a, b;
2804
2805 /* Are there nodes at this distance from each other? */
2806 if (!find_numa_distance(dist))
2807 continue;
2808
2809 for_each_node_mask(a, nodes) {
2810 unsigned long faults = 0;
2811 nodemask_t this_group;
2812 nodes_clear(this_group);
2813
2814 /* Sum group's NUMA faults; includes a==b case. */
2815 for_each_node_mask(b, nodes) {
2816 if (node_distance(a, b) < dist) {
2817 faults += group_faults(p, b);
2818 node_set(b, this_group);
2819 node_clear(b, nodes);
2820 }
2821 }
2822
2823 /* Remember the top group. */
2824 if (faults > max_faults) {
2825 max_faults = faults;
2826 max_group = this_group;
2827 /*
2828 * subtle: at the smallest distance there is
2829 * just one node left in each "group", the
2830 * winner is the preferred nid.
2831 */
2832 nid = a;
2833 }
2834 }
2835 /* Next round, evaluate the nodes within max_group. */
2836 if (!max_faults)
2837 break;
2838 nodes = max_group;
2839 }
2840 return nid;
2841 }
2842
task_numa_placement(struct task_struct * p)2843 static void task_numa_placement(struct task_struct *p)
2844 {
2845 int seq, nid, max_nid = NUMA_NO_NODE;
2846 unsigned long max_faults = 0;
2847 unsigned long fault_types[2] = { 0, 0 };
2848 unsigned long total_faults;
2849 u64 runtime, period;
2850 spinlock_t *group_lock = NULL;
2851 struct numa_group *ng;
2852
2853 /*
2854 * The p->mm->numa_scan_seq field gets updated without
2855 * exclusive access. Use READ_ONCE() here to ensure
2856 * that the field is read in a single access:
2857 */
2858 seq = READ_ONCE(p->mm->numa_scan_seq);
2859 if (p->numa_scan_seq == seq)
2860 return;
2861 p->numa_scan_seq = seq;
2862 p->numa_scan_period_max = task_scan_max(p);
2863
2864 total_faults = p->numa_faults_locality[0] +
2865 p->numa_faults_locality[1];
2866 runtime = numa_get_avg_runtime(p, &period);
2867
2868 /* If the task is part of a group prevent parallel updates to group stats */
2869 ng = deref_curr_numa_group(p);
2870 if (ng) {
2871 group_lock = &ng->lock;
2872 spin_lock_irq(group_lock);
2873 }
2874
2875 /* Find the node with the highest number of faults */
2876 for_each_online_node(nid) {
2877 /* Keep track of the offsets in numa_faults array */
2878 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
2879 unsigned long faults = 0, group_faults = 0;
2880 int priv;
2881
2882 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
2883 long diff, f_diff, f_weight;
2884
2885 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
2886 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
2887 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
2888 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
2889
2890 /* Decay existing window, copy faults since last scan */
2891 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
2892 fault_types[priv] += p->numa_faults[membuf_idx];
2893 p->numa_faults[membuf_idx] = 0;
2894
2895 /*
2896 * Normalize the faults_from, so all tasks in a group
2897 * count according to CPU use, instead of by the raw
2898 * number of faults. Tasks with little runtime have
2899 * little over-all impact on throughput, and thus their
2900 * faults are less important.
2901 */
2902 f_weight = div64_u64(runtime << 16, period + 1);
2903 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
2904 (total_faults + 1);
2905 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
2906 p->numa_faults[cpubuf_idx] = 0;
2907
2908 p->numa_faults[mem_idx] += diff;
2909 p->numa_faults[cpu_idx] += f_diff;
2910 faults += p->numa_faults[mem_idx];
2911 p->total_numa_faults += diff;
2912 if (ng) {
2913 /*
2914 * safe because we can only change our own group
2915 *
2916 * mem_idx represents the offset for a given
2917 * nid and priv in a specific region because it
2918 * is at the beginning of the numa_faults array.
2919 */
2920 ng->faults[mem_idx] += diff;
2921 ng->faults[cpu_idx] += f_diff;
2922 ng->total_faults += diff;
2923 group_faults += ng->faults[mem_idx];
2924 }
2925 }
2926
2927 if (!ng) {
2928 if (faults > max_faults) {
2929 max_faults = faults;
2930 max_nid = nid;
2931 }
2932 } else if (group_faults > max_faults) {
2933 max_faults = group_faults;
2934 max_nid = nid;
2935 }
2936 }
2937
2938 /* Cannot migrate task to CPU-less node */
2939 if (max_nid != NUMA_NO_NODE && !node_state(max_nid, N_CPU)) {
2940 int near_nid = max_nid;
2941 int distance, near_distance = INT_MAX;
2942
2943 for_each_node_state(nid, N_CPU) {
2944 distance = node_distance(max_nid, nid);
2945 if (distance < near_distance) {
2946 near_nid = nid;
2947 near_distance = distance;
2948 }
2949 }
2950 max_nid = near_nid;
2951 }
2952
2953 if (ng) {
2954 numa_group_count_active_nodes(ng);
2955 spin_unlock_irq(group_lock);
2956 max_nid = preferred_group_nid(p, max_nid);
2957 }
2958
2959 if (max_faults) {
2960 /* Set the new preferred node */
2961 if (max_nid != p->numa_preferred_nid)
2962 sched_setnuma(p, max_nid);
2963 }
2964
2965 update_task_scan_period(p, fault_types[0], fault_types[1]);
2966 }
2967
get_numa_group(struct numa_group * grp)2968 static inline int get_numa_group(struct numa_group *grp)
2969 {
2970 return refcount_inc_not_zero(&grp->refcount);
2971 }
2972
put_numa_group(struct numa_group * grp)2973 static inline void put_numa_group(struct numa_group *grp)
2974 {
2975 if (refcount_dec_and_test(&grp->refcount))
2976 kfree_rcu(grp, rcu);
2977 }
2978
task_numa_group(struct task_struct * p,int cpupid,int flags,int * priv)2979 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
2980 int *priv)
2981 {
2982 struct numa_group *grp, *my_grp;
2983 struct task_struct *tsk;
2984 bool join = false;
2985 int cpu = cpupid_to_cpu(cpupid);
2986 int i;
2987
2988 if (unlikely(!deref_curr_numa_group(p))) {
2989 unsigned int size = sizeof(struct numa_group) +
2990 NR_NUMA_HINT_FAULT_STATS *
2991 nr_node_ids * sizeof(unsigned long);
2992
2993 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
2994 if (!grp)
2995 return;
2996
2997 refcount_set(&grp->refcount, 1);
2998 grp->active_nodes = 1;
2999 grp->max_faults_cpu = 0;
3000 spin_lock_init(&grp->lock);
3001 grp->gid = p->pid;
3002
3003 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3004 grp->faults[i] = p->numa_faults[i];
3005
3006 grp->total_faults = p->total_numa_faults;
3007
3008 grp->nr_tasks++;
3009 rcu_assign_pointer(p->numa_group, grp);
3010 }
3011
3012 rcu_read_lock();
3013 tsk = READ_ONCE(cpu_rq(cpu)->curr);
3014
3015 if (!cpupid_match_pid(tsk, cpupid))
3016 goto no_join;
3017
3018 grp = rcu_dereference(tsk->numa_group);
3019 if (!grp)
3020 goto no_join;
3021
3022 my_grp = deref_curr_numa_group(p);
3023 if (grp == my_grp)
3024 goto no_join;
3025
3026 /*
3027 * Only join the other group if its bigger; if we're the bigger group,
3028 * the other task will join us.
3029 */
3030 if (my_grp->nr_tasks > grp->nr_tasks)
3031 goto no_join;
3032
3033 /*
3034 * Tie-break on the grp address.
3035 */
3036 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
3037 goto no_join;
3038
3039 /* Always join threads in the same process. */
3040 if (tsk->mm == current->mm)
3041 join = true;
3042
3043 /* Simple filter to avoid false positives due to PID collisions */
3044 if (flags & TNF_SHARED)
3045 join = true;
3046
3047 /* Update priv based on whether false sharing was detected */
3048 *priv = !join;
3049
3050 if (join && !get_numa_group(grp))
3051 goto no_join;
3052
3053 rcu_read_unlock();
3054
3055 if (!join)
3056 return;
3057
3058 WARN_ON_ONCE(irqs_disabled());
3059 double_lock_irq(&my_grp->lock, &grp->lock);
3060
3061 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
3062 my_grp->faults[i] -= p->numa_faults[i];
3063 grp->faults[i] += p->numa_faults[i];
3064 }
3065 my_grp->total_faults -= p->total_numa_faults;
3066 grp->total_faults += p->total_numa_faults;
3067
3068 my_grp->nr_tasks--;
3069 grp->nr_tasks++;
3070
3071 spin_unlock(&my_grp->lock);
3072 spin_unlock_irq(&grp->lock);
3073
3074 rcu_assign_pointer(p->numa_group, grp);
3075
3076 put_numa_group(my_grp);
3077 return;
3078
3079 no_join:
3080 rcu_read_unlock();
3081 return;
3082 }
3083
3084 /*
3085 * Get rid of NUMA statistics associated with a task (either current or dead).
3086 * If @final is set, the task is dead and has reached refcount zero, so we can
3087 * safely free all relevant data structures. Otherwise, there might be
3088 * concurrent reads from places like load balancing and procfs, and we should
3089 * reset the data back to default state without freeing ->numa_faults.
3090 */
task_numa_free(struct task_struct * p,bool final)3091 void task_numa_free(struct task_struct *p, bool final)
3092 {
3093 /* safe: p either is current or is being freed by current */
3094 struct numa_group *grp = rcu_dereference_raw(p->numa_group);
3095 unsigned long *numa_faults = p->numa_faults;
3096 unsigned long flags;
3097 int i;
3098
3099 if (!numa_faults)
3100 return;
3101
3102 if (grp) {
3103 spin_lock_irqsave(&grp->lock, flags);
3104 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3105 grp->faults[i] -= p->numa_faults[i];
3106 grp->total_faults -= p->total_numa_faults;
3107
3108 grp->nr_tasks--;
3109 spin_unlock_irqrestore(&grp->lock, flags);
3110 RCU_INIT_POINTER(p->numa_group, NULL);
3111 put_numa_group(grp);
3112 }
3113
3114 if (final) {
3115 p->numa_faults = NULL;
3116 kfree(numa_faults);
3117 } else {
3118 p->total_numa_faults = 0;
3119 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
3120 numa_faults[i] = 0;
3121 }
3122 }
3123
3124 /*
3125 * Got a PROT_NONE fault for a page on @node.
3126 */
task_numa_fault(int last_cpupid,int mem_node,int pages,int flags)3127 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
3128 {
3129 struct task_struct *p = current;
3130 bool migrated = flags & TNF_MIGRATED;
3131 int cpu_node = task_node(current);
3132 int local = !!(flags & TNF_FAULT_LOCAL);
3133 struct numa_group *ng;
3134 int priv;
3135
3136 if (!static_branch_likely(&sched_numa_balancing))
3137 return;
3138
3139 /* for example, ksmd faulting in a user's mm */
3140 if (!p->mm)
3141 return;
3142
3143 /*
3144 * NUMA faults statistics are unnecessary for the slow memory
3145 * node for memory tiering mode.
3146 */
3147 if (!node_is_toptier(mem_node) &&
3148 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING ||
3149 !cpupid_valid(last_cpupid)))
3150 return;
3151
3152 /* Allocate buffer to track faults on a per-node basis */
3153 if (unlikely(!p->numa_faults)) {
3154 int size = sizeof(*p->numa_faults) *
3155 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
3156
3157 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
3158 if (!p->numa_faults)
3159 return;
3160
3161 p->total_numa_faults = 0;
3162 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
3163 }
3164
3165 /*
3166 * First accesses are treated as private, otherwise consider accesses
3167 * to be private if the accessing pid has not changed
3168 */
3169 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
3170 priv = 1;
3171 } else {
3172 priv = cpupid_match_pid(p, last_cpupid);
3173 if (!priv && !(flags & TNF_NO_GROUP))
3174 task_numa_group(p, last_cpupid, flags, &priv);
3175 }
3176
3177 /*
3178 * If a workload spans multiple NUMA nodes, a shared fault that
3179 * occurs wholly within the set of nodes that the workload is
3180 * actively using should be counted as local. This allows the
3181 * scan rate to slow down when a workload has settled down.
3182 */
3183 ng = deref_curr_numa_group(p);
3184 if (!priv && !local && ng && ng->active_nodes > 1 &&
3185 numa_is_active_node(cpu_node, ng) &&
3186 numa_is_active_node(mem_node, ng))
3187 local = 1;
3188
3189 /*
3190 * Retry to migrate task to preferred node periodically, in case it
3191 * previously failed, or the scheduler moved us.
3192 */
3193 if (time_after(jiffies, p->numa_migrate_retry)) {
3194 task_numa_placement(p);
3195 numa_migrate_preferred(p);
3196 }
3197
3198 if (migrated)
3199 p->numa_pages_migrated += pages;
3200 if (flags & TNF_MIGRATE_FAIL)
3201 p->numa_faults_locality[2] += pages;
3202
3203 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
3204 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
3205 p->numa_faults_locality[local] += pages;
3206 }
3207
reset_ptenuma_scan(struct task_struct * p)3208 static void reset_ptenuma_scan(struct task_struct *p)
3209 {
3210 /*
3211 * We only did a read acquisition of the mmap sem, so
3212 * p->mm->numa_scan_seq is written to without exclusive access
3213 * and the update is not guaranteed to be atomic. That's not
3214 * much of an issue though, since this is just used for
3215 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not
3216 * expensive, to avoid any form of compiler optimizations:
3217 */
3218 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1);
3219 p->mm->numa_scan_offset = 0;
3220 }
3221
vma_is_accessed(struct vm_area_struct * vma)3222 static bool vma_is_accessed(struct vm_area_struct *vma)
3223 {
3224 unsigned long pids;
3225 /*
3226 * Allow unconditional access first two times, so that all the (pages)
3227 * of VMAs get prot_none fault introduced irrespective of accesses.
3228 * This is also done to avoid any side effect of task scanning
3229 * amplifying the unfairness of disjoint set of VMAs' access.
3230 */
3231 if (READ_ONCE(current->mm->numa_scan_seq) < 2)
3232 return true;
3233
3234 pids = vma->numab_state->access_pids[0] | vma->numab_state->access_pids[1];
3235 return test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids);
3236 }
3237
3238 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay)
3239
3240 /*
3241 * The expensive part of numa migration is done from task_work context.
3242 * Triggered from task_tick_numa().
3243 */
task_numa_work(struct callback_head * work)3244 static void task_numa_work(struct callback_head *work)
3245 {
3246 unsigned long migrate, next_scan, now = jiffies;
3247 struct task_struct *p = current;
3248 struct mm_struct *mm = p->mm;
3249 u64 runtime = p->se.sum_exec_runtime;
3250 struct vm_area_struct *vma;
3251 unsigned long start, end;
3252 unsigned long nr_pte_updates = 0;
3253 long pages, virtpages;
3254 struct vma_iterator vmi;
3255
3256 SCHED_WARN_ON(p != container_of(work, struct task_struct, numa_work));
3257
3258 work->next = work;
3259 /*
3260 * Who cares about NUMA placement when they're dying.
3261 *
3262 * NOTE: make sure not to dereference p->mm before this check,
3263 * exit_task_work() happens _after_ exit_mm() so we could be called
3264 * without p->mm even though we still had it when we enqueued this
3265 * work.
3266 */
3267 if (p->flags & PF_EXITING)
3268 return;
3269
3270 if (!mm->numa_next_scan) {
3271 mm->numa_next_scan = now +
3272 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3273 }
3274
3275 /*
3276 * Enforce maximal scan/migration frequency..
3277 */
3278 migrate = mm->numa_next_scan;
3279 if (time_before(now, migrate))
3280 return;
3281
3282 if (p->numa_scan_period == 0) {
3283 p->numa_scan_period_max = task_scan_max(p);
3284 p->numa_scan_period = task_scan_start(p);
3285 }
3286
3287 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
3288 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan))
3289 return;
3290
3291 /*
3292 * Delay this task enough that another task of this mm will likely win
3293 * the next time around.
3294 */
3295 p->node_stamp += 2 * TICK_NSEC;
3296
3297 start = mm->numa_scan_offset;
3298 pages = sysctl_numa_balancing_scan_size;
3299 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
3300 virtpages = pages * 8; /* Scan up to this much virtual space */
3301 if (!pages)
3302 return;
3303
3304
3305 if (!mmap_read_trylock(mm))
3306 return;
3307 vma_iter_init(&vmi, mm, start);
3308 vma = vma_next(&vmi);
3309 if (!vma) {
3310 reset_ptenuma_scan(p);
3311 start = 0;
3312 vma_iter_set(&vmi, start);
3313 vma = vma_next(&vmi);
3314 }
3315
3316 do {
3317 if (!vma_migratable(vma) || !vma_policy_mof(vma) ||
3318 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) {
3319 continue;
3320 }
3321
3322 /*
3323 * Shared library pages mapped by multiple processes are not
3324 * migrated as it is expected they are cache replicated. Avoid
3325 * hinting faults in read-only file-backed mappings or the vdso
3326 * as migrating the pages will be of marginal benefit.
3327 */
3328 if (!vma->vm_mm ||
3329 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
3330 continue;
3331
3332 /*
3333 * Skip inaccessible VMAs to avoid any confusion between
3334 * PROT_NONE and NUMA hinting ptes
3335 */
3336 if (!vma_is_accessible(vma))
3337 continue;
3338
3339 /* Initialise new per-VMA NUMAB state. */
3340 if (!vma->numab_state) {
3341 vma->numab_state = kzalloc(sizeof(struct vma_numab_state),
3342 GFP_KERNEL);
3343 if (!vma->numab_state)
3344 continue;
3345
3346 vma->numab_state->next_scan = now +
3347 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3348
3349 /* Reset happens after 4 times scan delay of scan start */
3350 vma->numab_state->next_pid_reset = vma->numab_state->next_scan +
3351 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3352 }
3353
3354 /*
3355 * Scanning the VMA's of short lived tasks add more overhead. So
3356 * delay the scan for new VMAs.
3357 */
3358 if (mm->numa_scan_seq && time_before(jiffies,
3359 vma->numab_state->next_scan))
3360 continue;
3361
3362 /* Do not scan the VMA if task has not accessed */
3363 if (!vma_is_accessed(vma))
3364 continue;
3365
3366 /*
3367 * RESET access PIDs regularly for old VMAs. Resetting after checking
3368 * vma for recent access to avoid clearing PID info before access..
3369 */
3370 if (mm->numa_scan_seq &&
3371 time_after(jiffies, vma->numab_state->next_pid_reset)) {
3372 vma->numab_state->next_pid_reset = vma->numab_state->next_pid_reset +
3373 msecs_to_jiffies(VMA_PID_RESET_PERIOD);
3374 vma->numab_state->access_pids[0] = READ_ONCE(vma->numab_state->access_pids[1]);
3375 vma->numab_state->access_pids[1] = 0;
3376 }
3377
3378 do {
3379 start = max(start, vma->vm_start);
3380 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
3381 end = min(end, vma->vm_end);
3382 nr_pte_updates = change_prot_numa(vma, start, end);
3383
3384 /*
3385 * Try to scan sysctl_numa_balancing_size worth of
3386 * hpages that have at least one present PTE that
3387 * is not already pte-numa. If the VMA contains
3388 * areas that are unused or already full of prot_numa
3389 * PTEs, scan up to virtpages, to skip through those
3390 * areas faster.
3391 */
3392 if (nr_pte_updates)
3393 pages -= (end - start) >> PAGE_SHIFT;
3394 virtpages -= (end - start) >> PAGE_SHIFT;
3395
3396 start = end;
3397 if (pages <= 0 || virtpages <= 0)
3398 goto out;
3399
3400 cond_resched();
3401 } while (end != vma->vm_end);
3402 } for_each_vma(vmi, vma);
3403
3404 out:
3405 /*
3406 * It is possible to reach the end of the VMA list but the last few
3407 * VMAs are not guaranteed to the vma_migratable. If they are not, we
3408 * would find the !migratable VMA on the next scan but not reset the
3409 * scanner to the start so check it now.
3410 */
3411 if (vma)
3412 mm->numa_scan_offset = start;
3413 else
3414 reset_ptenuma_scan(p);
3415 mmap_read_unlock(mm);
3416
3417 /*
3418 * Make sure tasks use at least 32x as much time to run other code
3419 * than they used here, to limit NUMA PTE scanning overhead to 3% max.
3420 * Usually update_task_scan_period slows down scanning enough; on an
3421 * overloaded system we need to limit overhead on a per task basis.
3422 */
3423 if (unlikely(p->se.sum_exec_runtime != runtime)) {
3424 u64 diff = p->se.sum_exec_runtime - runtime;
3425 p->node_stamp += 32 * diff;
3426 }
3427 }
3428
init_numa_balancing(unsigned long clone_flags,struct task_struct * p)3429 void init_numa_balancing(unsigned long clone_flags, struct task_struct *p)
3430 {
3431 int mm_users = 0;
3432 struct mm_struct *mm = p->mm;
3433
3434 if (mm) {
3435 mm_users = atomic_read(&mm->mm_users);
3436 if (mm_users == 1) {
3437 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
3438 mm->numa_scan_seq = 0;
3439 }
3440 }
3441 p->node_stamp = 0;
3442 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0;
3443 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
3444 p->numa_migrate_retry = 0;
3445 /* Protect against double add, see task_tick_numa and task_numa_work */
3446 p->numa_work.next = &p->numa_work;
3447 p->numa_faults = NULL;
3448 p->numa_pages_migrated = 0;
3449 p->total_numa_faults = 0;
3450 RCU_INIT_POINTER(p->numa_group, NULL);
3451 p->last_task_numa_placement = 0;
3452 p->last_sum_exec_runtime = 0;
3453
3454 init_task_work(&p->numa_work, task_numa_work);
3455
3456 /* New address space, reset the preferred nid */
3457 if (!(clone_flags & CLONE_VM)) {
3458 p->numa_preferred_nid = NUMA_NO_NODE;
3459 return;
3460 }
3461
3462 /*
3463 * New thread, keep existing numa_preferred_nid which should be copied
3464 * already by arch_dup_task_struct but stagger when scans start.
3465 */
3466 if (mm) {
3467 unsigned int delay;
3468
3469 delay = min_t(unsigned int, task_scan_max(current),
3470 current->numa_scan_period * mm_users * NSEC_PER_MSEC);
3471 delay += 2 * TICK_NSEC;
3472 p->node_stamp = delay;
3473 }
3474 }
3475
3476 /*
3477 * Drive the periodic memory faults..
3478 */
task_tick_numa(struct rq * rq,struct task_struct * curr)3479 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3480 {
3481 struct callback_head *work = &curr->numa_work;
3482 u64 period, now;
3483
3484 /*
3485 * We don't care about NUMA placement if we don't have memory.
3486 */
3487 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work)
3488 return;
3489
3490 /*
3491 * Using runtime rather than walltime has the dual advantage that
3492 * we (mostly) drive the selection from busy threads and that the
3493 * task needs to have done some actual work before we bother with
3494 * NUMA placement.
3495 */
3496 now = curr->se.sum_exec_runtime;
3497 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
3498
3499 if (now > curr->node_stamp + period) {
3500 if (!curr->node_stamp)
3501 curr->numa_scan_period = task_scan_start(curr);
3502 curr->node_stamp += period;
3503
3504 if (!time_before(jiffies, curr->mm->numa_next_scan))
3505 task_work_add(curr, work, TWA_RESUME);
3506 }
3507 }
3508
update_scan_period(struct task_struct * p,int new_cpu)3509 static void update_scan_period(struct task_struct *p, int new_cpu)
3510 {
3511 int src_nid = cpu_to_node(task_cpu(p));
3512 int dst_nid = cpu_to_node(new_cpu);
3513
3514 if (!static_branch_likely(&sched_numa_balancing))
3515 return;
3516
3517 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING))
3518 return;
3519
3520 if (src_nid == dst_nid)
3521 return;
3522
3523 /*
3524 * Allow resets if faults have been trapped before one scan
3525 * has completed. This is most likely due to a new task that
3526 * is pulled cross-node due to wakeups or load balancing.
3527 */
3528 if (p->numa_scan_seq) {
3529 /*
3530 * Avoid scan adjustments if moving to the preferred
3531 * node or if the task was not previously running on
3532 * the preferred node.
3533 */
3534 if (dst_nid == p->numa_preferred_nid ||
3535 (p->numa_preferred_nid != NUMA_NO_NODE &&
3536 src_nid != p->numa_preferred_nid))
3537 return;
3538 }
3539
3540 p->numa_scan_period = task_scan_start(p);
3541 }
3542
3543 #else
task_tick_numa(struct rq * rq,struct task_struct * curr)3544 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
3545 {
3546 }
3547
account_numa_enqueue(struct rq * rq,struct task_struct * p)3548 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
3549 {
3550 }
3551
account_numa_dequeue(struct rq * rq,struct task_struct * p)3552 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
3553 {
3554 }
3555
update_scan_period(struct task_struct * p,int new_cpu)3556 static inline void update_scan_period(struct task_struct *p, int new_cpu)
3557 {
3558 }
3559
3560 #endif /* CONFIG_NUMA_BALANCING */
3561
3562 static void
account_entity_enqueue(struct cfs_rq * cfs_rq,struct sched_entity * se)3563 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3564 {
3565 update_load_add(&cfs_rq->load, se->load.weight);
3566 #ifdef CONFIG_SMP
3567 if (entity_is_task(se)) {
3568 struct rq *rq = rq_of(cfs_rq);
3569
3570 account_numa_enqueue(rq, task_of(se));
3571 list_add(&se->group_node, &rq->cfs_tasks);
3572 }
3573 #endif
3574 cfs_rq->nr_running++;
3575 if (se_is_idle(se))
3576 cfs_rq->idle_nr_running++;
3577 }
3578
3579 static void
account_entity_dequeue(struct cfs_rq * cfs_rq,struct sched_entity * se)3580 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
3581 {
3582 update_load_sub(&cfs_rq->load, se->load.weight);
3583 #ifdef CONFIG_SMP
3584 if (entity_is_task(se)) {
3585 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
3586 list_del_init(&se->group_node);
3587 }
3588 #endif
3589 cfs_rq->nr_running--;
3590 if (se_is_idle(se))
3591 cfs_rq->idle_nr_running--;
3592 }
3593
3594 /*
3595 * Signed add and clamp on underflow.
3596 *
3597 * Explicitly do a load-store to ensure the intermediate value never hits
3598 * memory. This allows lockless observations without ever seeing the negative
3599 * values.
3600 */
3601 #define add_positive(_ptr, _val) do { \
3602 typeof(_ptr) ptr = (_ptr); \
3603 typeof(_val) val = (_val); \
3604 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3605 \
3606 res = var + val; \
3607 \
3608 if (val < 0 && res > var) \
3609 res = 0; \
3610 \
3611 WRITE_ONCE(*ptr, res); \
3612 } while (0)
3613
3614 /*
3615 * Unsigned subtract and clamp on underflow.
3616 *
3617 * Explicitly do a load-store to ensure the intermediate value never hits
3618 * memory. This allows lockless observations without ever seeing the negative
3619 * values.
3620 */
3621 #define sub_positive(_ptr, _val) do { \
3622 typeof(_ptr) ptr = (_ptr); \
3623 typeof(*ptr) val = (_val); \
3624 typeof(*ptr) res, var = READ_ONCE(*ptr); \
3625 res = var - val; \
3626 if (res > var) \
3627 res = 0; \
3628 WRITE_ONCE(*ptr, res); \
3629 } while (0)
3630
3631 /*
3632 * Remove and clamp on negative, from a local variable.
3633 *
3634 * A variant of sub_positive(), which does not use explicit load-store
3635 * and is thus optimized for local variable updates.
3636 */
3637 #define lsub_positive(_ptr, _val) do { \
3638 typeof(_ptr) ptr = (_ptr); \
3639 *ptr -= min_t(typeof(*ptr), *ptr, _val); \
3640 } while (0)
3641
3642 #ifdef CONFIG_SMP
3643 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3644 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3645 {
3646 cfs_rq->avg.load_avg += se->avg.load_avg;
3647 cfs_rq->avg.load_sum += se_weight(se) * se->avg.load_sum;
3648 }
3649
3650 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3651 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
3652 {
3653 sub_positive(&cfs_rq->avg.load_avg, se->avg.load_avg);
3654 sub_positive(&cfs_rq->avg.load_sum, se_weight(se) * se->avg.load_sum);
3655 /* See update_cfs_rq_load_avg() */
3656 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
3657 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
3658 }
3659 #else
3660 static inline void
enqueue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3661 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3662 static inline void
dequeue_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)3663 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) { }
3664 #endif
3665
reweight_eevdf(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3666 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se,
3667 unsigned long weight)
3668 {
3669 unsigned long old_weight = se->load.weight;
3670 u64 avruntime = avg_vruntime(cfs_rq);
3671 s64 vlag, vslice;
3672
3673 /*
3674 * VRUNTIME
3675 * ========
3676 *
3677 * COROLLARY #1: The virtual runtime of the entity needs to be
3678 * adjusted if re-weight at !0-lag point.
3679 *
3680 * Proof: For contradiction assume this is not true, so we can
3681 * re-weight without changing vruntime at !0-lag point.
3682 *
3683 * Weight VRuntime Avg-VRuntime
3684 * before w v V
3685 * after w' v' V'
3686 *
3687 * Since lag needs to be preserved through re-weight:
3688 *
3689 * lag = (V - v)*w = (V'- v')*w', where v = v'
3690 * ==> V' = (V - v)*w/w' + v (1)
3691 *
3692 * Let W be the total weight of the entities before reweight,
3693 * since V' is the new weighted average of entities:
3694 *
3695 * V' = (WV + w'v - wv) / (W + w' - w) (2)
3696 *
3697 * by using (1) & (2) we obtain:
3698 *
3699 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v
3700 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v
3701 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v
3702 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3)
3703 *
3704 * Since we are doing at !0-lag point which means V != v, we
3705 * can simplify (3):
3706 *
3707 * ==> W / (W + w' - w) = w / w'
3708 * ==> Ww' = Ww + ww' - ww
3709 * ==> W * (w' - w) = w * (w' - w)
3710 * ==> W = w (re-weight indicates w' != w)
3711 *
3712 * So the cfs_rq contains only one entity, hence vruntime of
3713 * the entity @v should always equal to the cfs_rq's weighted
3714 * average vruntime @V, which means we will always re-weight
3715 * at 0-lag point, thus breach assumption. Proof completed.
3716 *
3717 *
3718 * COROLLARY #2: Re-weight does NOT affect weighted average
3719 * vruntime of all the entities.
3720 *
3721 * Proof: According to corollary #1, Eq. (1) should be:
3722 *
3723 * (V - v)*w = (V' - v')*w'
3724 * ==> v' = V' - (V - v)*w/w' (4)
3725 *
3726 * According to the weighted average formula, we have:
3727 *
3728 * V' = (WV - wv + w'v') / (W - w + w')
3729 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w')
3730 * = (WV - wv + w'V' - Vw + wv) / (W - w + w')
3731 * = (WV + w'V' - Vw) / (W - w + w')
3732 *
3733 * ==> V'*(W - w + w') = WV + w'V' - Vw
3734 * ==> V' * (W - w) = (W - w) * V (5)
3735 *
3736 * If the entity is the only one in the cfs_rq, then reweight
3737 * always occurs at 0-lag point, so V won't change. Or else
3738 * there are other entities, hence W != w, then Eq. (5) turns
3739 * into V' = V. So V won't change in either case, proof done.
3740 *
3741 *
3742 * So according to corollary #1 & #2, the effect of re-weight
3743 * on vruntime should be:
3744 *
3745 * v' = V' - (V - v) * w / w' (4)
3746 * = V - (V - v) * w / w'
3747 * = V - vl * w / w'
3748 * = V - vl'
3749 */
3750 if (avruntime != se->vruntime) {
3751 vlag = (s64)(avruntime - se->vruntime);
3752 vlag = div_s64(vlag * old_weight, weight);
3753 se->vruntime = avruntime - vlag;
3754 }
3755
3756 /*
3757 * DEADLINE
3758 * ========
3759 *
3760 * When the weight changes, the virtual time slope changes and
3761 * we should adjust the relative virtual deadline accordingly.
3762 *
3763 * d' = v' + (d - v)*w/w'
3764 * = V' - (V - v)*w/w' + (d - v)*w/w'
3765 * = V - (V - v)*w/w' + (d - v)*w/w'
3766 * = V + (d - V)*w/w'
3767 */
3768 vslice = (s64)(se->deadline - avruntime);
3769 vslice = div_s64(vslice * old_weight, weight);
3770 se->deadline = avruntime + vslice;
3771 }
3772
reweight_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,unsigned long weight)3773 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
3774 unsigned long weight)
3775 {
3776 bool curr = cfs_rq->curr == se;
3777
3778 if (se->on_rq) {
3779 /* commit outstanding execution time */
3780 if (curr)
3781 update_curr(cfs_rq);
3782 else
3783 __dequeue_entity(cfs_rq, se);
3784 update_load_sub(&cfs_rq->load, se->load.weight);
3785 }
3786 dequeue_load_avg(cfs_rq, se);
3787
3788 if (!se->on_rq) {
3789 /*
3790 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i),
3791 * we need to scale se->vlag when w_i changes.
3792 */
3793 se->vlag = div_s64(se->vlag * se->load.weight, weight);
3794 } else {
3795 reweight_eevdf(cfs_rq, se, weight);
3796 }
3797
3798 update_load_set(&se->load, weight);
3799
3800 #ifdef CONFIG_SMP
3801 do {
3802 u32 divider = get_pelt_divider(&se->avg);
3803
3804 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider);
3805 } while (0);
3806 #endif
3807
3808 enqueue_load_avg(cfs_rq, se);
3809 if (se->on_rq) {
3810 update_load_add(&cfs_rq->load, se->load.weight);
3811 if (!curr)
3812 __enqueue_entity(cfs_rq, se);
3813
3814 /*
3815 * The entity's vruntime has been adjusted, so let's check
3816 * whether the rq-wide min_vruntime needs updated too. Since
3817 * the calculations above require stable min_vruntime rather
3818 * than up-to-date one, we do the update at the end of the
3819 * reweight process.
3820 */
3821 update_min_vruntime(cfs_rq);
3822 }
3823 }
3824
reweight_task(struct task_struct * p,int prio)3825 void reweight_task(struct task_struct *p, int prio)
3826 {
3827 struct sched_entity *se = &p->se;
3828 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3829 struct load_weight *load = &se->load;
3830 unsigned long weight = scale_load(sched_prio_to_weight[prio]);
3831
3832 reweight_entity(cfs_rq, se, weight);
3833 load->inv_weight = sched_prio_to_wmult[prio];
3834 }
3835
3836 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
3837
3838 #ifdef CONFIG_FAIR_GROUP_SCHED
3839 #ifdef CONFIG_SMP
3840 /*
3841 * All this does is approximate the hierarchical proportion which includes that
3842 * global sum we all love to hate.
3843 *
3844 * That is, the weight of a group entity, is the proportional share of the
3845 * group weight based on the group runqueue weights. That is:
3846 *
3847 * tg->weight * grq->load.weight
3848 * ge->load.weight = ----------------------------- (1)
3849 * \Sum grq->load.weight
3850 *
3851 * Now, because computing that sum is prohibitively expensive to compute (been
3852 * there, done that) we approximate it with this average stuff. The average
3853 * moves slower and therefore the approximation is cheaper and more stable.
3854 *
3855 * So instead of the above, we substitute:
3856 *
3857 * grq->load.weight -> grq->avg.load_avg (2)
3858 *
3859 * which yields the following:
3860 *
3861 * tg->weight * grq->avg.load_avg
3862 * ge->load.weight = ------------------------------ (3)
3863 * tg->load_avg
3864 *
3865 * Where: tg->load_avg ~= \Sum grq->avg.load_avg
3866 *
3867 * That is shares_avg, and it is right (given the approximation (2)).
3868 *
3869 * The problem with it is that because the average is slow -- it was designed
3870 * to be exactly that of course -- this leads to transients in boundary
3871 * conditions. In specific, the case where the group was idle and we start the
3872 * one task. It takes time for our CPU's grq->avg.load_avg to build up,
3873 * yielding bad latency etc..
3874 *
3875 * Now, in that special case (1) reduces to:
3876 *
3877 * tg->weight * grq->load.weight
3878 * ge->load.weight = ----------------------------- = tg->weight (4)
3879 * grp->load.weight
3880 *
3881 * That is, the sum collapses because all other CPUs are idle; the UP scenario.
3882 *
3883 * So what we do is modify our approximation (3) to approach (4) in the (near)
3884 * UP case, like:
3885 *
3886 * ge->load.weight =
3887 *
3888 * tg->weight * grq->load.weight
3889 * --------------------------------------------------- (5)
3890 * tg->load_avg - grq->avg.load_avg + grq->load.weight
3891 *
3892 * But because grq->load.weight can drop to 0, resulting in a divide by zero,
3893 * we need to use grq->avg.load_avg as its lower bound, which then gives:
3894 *
3895 *
3896 * tg->weight * grq->load.weight
3897 * ge->load.weight = ----------------------------- (6)
3898 * tg_load_avg'
3899 *
3900 * Where:
3901 *
3902 * tg_load_avg' = tg->load_avg - grq->avg.load_avg +
3903 * max(grq->load.weight, grq->avg.load_avg)
3904 *
3905 * And that is shares_weight and is icky. In the (near) UP case it approaches
3906 * (4) while in the normal case it approaches (3). It consistently
3907 * overestimates the ge->load.weight and therefore:
3908 *
3909 * \Sum ge->load.weight >= tg->weight
3910 *
3911 * hence icky!
3912 */
calc_group_shares(struct cfs_rq * cfs_rq)3913 static long calc_group_shares(struct cfs_rq *cfs_rq)
3914 {
3915 long tg_weight, tg_shares, load, shares;
3916 struct task_group *tg = cfs_rq->tg;
3917
3918 tg_shares = READ_ONCE(tg->shares);
3919
3920 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg);
3921
3922 tg_weight = atomic_long_read(&tg->load_avg);
3923
3924 /* Ensure tg_weight >= load */
3925 tg_weight -= cfs_rq->tg_load_avg_contrib;
3926 tg_weight += load;
3927
3928 shares = (tg_shares * load);
3929 if (tg_weight)
3930 shares /= tg_weight;
3931
3932 /*
3933 * MIN_SHARES has to be unscaled here to support per-CPU partitioning
3934 * of a group with small tg->shares value. It is a floor value which is
3935 * assigned as a minimum load.weight to the sched_entity representing
3936 * the group on a CPU.
3937 *
3938 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024
3939 * on an 8-core system with 8 tasks each runnable on one CPU shares has
3940 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In
3941 * case no task is runnable on a CPU MIN_SHARES=2 should be returned
3942 * instead of 0.
3943 */
3944 return clamp_t(long, shares, MIN_SHARES, tg_shares);
3945 }
3946 #endif /* CONFIG_SMP */
3947
3948 /*
3949 * Recomputes the group entity based on the current state of its group
3950 * runqueue.
3951 */
update_cfs_group(struct sched_entity * se)3952 static void update_cfs_group(struct sched_entity *se)
3953 {
3954 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
3955 long shares;
3956
3957 if (!gcfs_rq)
3958 return;
3959
3960 if (throttled_hierarchy(gcfs_rq))
3961 return;
3962
3963 #ifndef CONFIG_SMP
3964 shares = READ_ONCE(gcfs_rq->tg->shares);
3965 #else
3966 shares = calc_group_shares(gcfs_rq);
3967 #endif
3968 if (unlikely(se->load.weight != shares))
3969 reweight_entity(cfs_rq_of(se), se, shares);
3970 }
3971
3972 #else /* CONFIG_FAIR_GROUP_SCHED */
update_cfs_group(struct sched_entity * se)3973 static inline void update_cfs_group(struct sched_entity *se)
3974 {
3975 }
3976 #endif /* CONFIG_FAIR_GROUP_SCHED */
3977
cfs_rq_util_change(struct cfs_rq * cfs_rq,int flags)3978 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags)
3979 {
3980 struct rq *rq = rq_of(cfs_rq);
3981
3982 if (&rq->cfs == cfs_rq) {
3983 /*
3984 * There are a few boundary cases this might miss but it should
3985 * get called often enough that that should (hopefully) not be
3986 * a real problem.
3987 *
3988 * It will not get called when we go idle, because the idle
3989 * thread is a different class (!fair), nor will the utilization
3990 * number include things like RT tasks.
3991 *
3992 * As is, the util number is not freq-invariant (we'd have to
3993 * implement arch_scale_freq_capacity() for that).
3994 *
3995 * See cpu_util_cfs().
3996 */
3997 cpufreq_update_util(rq, flags);
3998 }
3999 }
4000
4001 #ifdef CONFIG_SMP
load_avg_is_decayed(struct sched_avg * sa)4002 static inline bool load_avg_is_decayed(struct sched_avg *sa)
4003 {
4004 if (sa->load_sum)
4005 return false;
4006
4007 if (sa->util_sum)
4008 return false;
4009
4010 if (sa->runnable_sum)
4011 return false;
4012
4013 /*
4014 * _avg must be null when _sum are null because _avg = _sum / divider
4015 * Make sure that rounding and/or propagation of PELT values never
4016 * break this.
4017 */
4018 SCHED_WARN_ON(sa->load_avg ||
4019 sa->util_avg ||
4020 sa->runnable_avg);
4021
4022 return true;
4023 }
4024
cfs_rq_last_update_time(struct cfs_rq * cfs_rq)4025 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq)
4026 {
4027 return u64_u32_load_copy(cfs_rq->avg.last_update_time,
4028 cfs_rq->last_update_time_copy);
4029 }
4030 #ifdef CONFIG_FAIR_GROUP_SCHED
4031 /*
4032 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list
4033 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list
4034 * bottom-up, we only have to test whether the cfs_rq before us on the list
4035 * is our child.
4036 * If cfs_rq is not on the list, test whether a child needs its to be added to
4037 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details).
4038 */
child_cfs_rq_on_list(struct cfs_rq * cfs_rq)4039 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq)
4040 {
4041 struct cfs_rq *prev_cfs_rq;
4042 struct list_head *prev;
4043
4044 if (cfs_rq->on_list) {
4045 prev = cfs_rq->leaf_cfs_rq_list.prev;
4046 } else {
4047 struct rq *rq = rq_of(cfs_rq);
4048
4049 prev = rq->tmp_alone_branch;
4050 }
4051
4052 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list);
4053
4054 return (prev_cfs_rq->tg->parent == cfs_rq->tg);
4055 }
4056
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)4057 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
4058 {
4059 if (cfs_rq->load.weight)
4060 return false;
4061
4062 if (!load_avg_is_decayed(&cfs_rq->avg))
4063 return false;
4064
4065 if (child_cfs_rq_on_list(cfs_rq))
4066 return false;
4067
4068 return true;
4069 }
4070
4071 /**
4072 * update_tg_load_avg - update the tg's load avg
4073 * @cfs_rq: the cfs_rq whose avg changed
4074 *
4075 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load.
4076 * However, because tg->load_avg is a global value there are performance
4077 * considerations.
4078 *
4079 * In order to avoid having to look at the other cfs_rq's, we use a
4080 * differential update where we store the last value we propagated. This in
4081 * turn allows skipping updates if the differential is 'small'.
4082 *
4083 * Updating tg's load_avg is necessary before update_cfs_share().
4084 */
update_tg_load_avg(struct cfs_rq * cfs_rq)4085 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq)
4086 {
4087 long delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib;
4088
4089 /*
4090 * No need to update load_avg for root_task_group as it is not used.
4091 */
4092 if (cfs_rq->tg == &root_task_group)
4093 return;
4094
4095 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) {
4096 atomic_long_add(delta, &cfs_rq->tg->load_avg);
4097 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg;
4098 }
4099 }
4100
4101 /*
4102 * Called within set_task_rq() right before setting a task's CPU. The
4103 * caller only guarantees p->pi_lock is held; no other assumptions,
4104 * including the state of rq->lock, should be made.
4105 */
set_task_rq_fair(struct sched_entity * se,struct cfs_rq * prev,struct cfs_rq * next)4106 void set_task_rq_fair(struct sched_entity *se,
4107 struct cfs_rq *prev, struct cfs_rq *next)
4108 {
4109 u64 p_last_update_time;
4110 u64 n_last_update_time;
4111
4112 if (!sched_feat(ATTACH_AGE_LOAD))
4113 return;
4114
4115 /*
4116 * We are supposed to update the task to "current" time, then its up to
4117 * date and ready to go to new CPU/cfs_rq. But we have difficulty in
4118 * getting what current time is, so simply throw away the out-of-date
4119 * time. This will result in the wakee task is less decayed, but giving
4120 * the wakee more load sounds not bad.
4121 */
4122 if (!(se->avg.last_update_time && prev))
4123 return;
4124
4125 p_last_update_time = cfs_rq_last_update_time(prev);
4126 n_last_update_time = cfs_rq_last_update_time(next);
4127
4128 __update_load_avg_blocked_se(p_last_update_time, se);
4129 se->avg.last_update_time = n_last_update_time;
4130 }
4131
4132 /*
4133 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to
4134 * propagate its contribution. The key to this propagation is the invariant
4135 * that for each group:
4136 *
4137 * ge->avg == grq->avg (1)
4138 *
4139 * _IFF_ we look at the pure running and runnable sums. Because they
4140 * represent the very same entity, just at different points in the hierarchy.
4141 *
4142 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial
4143 * and simply copies the running/runnable sum over (but still wrong, because
4144 * the group entity and group rq do not have their PELT windows aligned).
4145 *
4146 * However, update_tg_cfs_load() is more complex. So we have:
4147 *
4148 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2)
4149 *
4150 * And since, like util, the runnable part should be directly transferable,
4151 * the following would _appear_ to be the straight forward approach:
4152 *
4153 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3)
4154 *
4155 * And per (1) we have:
4156 *
4157 * ge->avg.runnable_avg == grq->avg.runnable_avg
4158 *
4159 * Which gives:
4160 *
4161 * ge->load.weight * grq->avg.load_avg
4162 * ge->avg.load_avg = ----------------------------------- (4)
4163 * grq->load.weight
4164 *
4165 * Except that is wrong!
4166 *
4167 * Because while for entities historical weight is not important and we
4168 * really only care about our future and therefore can consider a pure
4169 * runnable sum, runqueues can NOT do this.
4170 *
4171 * We specifically want runqueues to have a load_avg that includes
4172 * historical weights. Those represent the blocked load, the load we expect
4173 * to (shortly) return to us. This only works by keeping the weights as
4174 * integral part of the sum. We therefore cannot decompose as per (3).
4175 *
4176 * Another reason this doesn't work is that runnable isn't a 0-sum entity.
4177 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the
4178 * rq itself is runnable anywhere between 2/3 and 1 depending on how the
4179 * runnable section of these tasks overlap (or not). If they were to perfectly
4180 * align the rq as a whole would be runnable 2/3 of the time. If however we
4181 * always have at least 1 runnable task, the rq as a whole is always runnable.
4182 *
4183 * So we'll have to approximate.. :/
4184 *
4185 * Given the constraint:
4186 *
4187 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX
4188 *
4189 * We can construct a rule that adds runnable to a rq by assuming minimal
4190 * overlap.
4191 *
4192 * On removal, we'll assume each task is equally runnable; which yields:
4193 *
4194 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight
4195 *
4196 * XXX: only do this for the part of runnable > running ?
4197 *
4198 */
4199 static inline void
update_tg_cfs_util(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4200 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4201 {
4202 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg;
4203 u32 new_sum, divider;
4204
4205 /* Nothing to update */
4206 if (!delta_avg)
4207 return;
4208
4209 /*
4210 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4211 * See ___update_load_avg() for details.
4212 */
4213 divider = get_pelt_divider(&cfs_rq->avg);
4214
4215
4216 /* Set new sched_entity's utilization */
4217 se->avg.util_avg = gcfs_rq->avg.util_avg;
4218 new_sum = se->avg.util_avg * divider;
4219 delta_sum = (long)new_sum - (long)se->avg.util_sum;
4220 se->avg.util_sum = new_sum;
4221
4222 /* Update parent cfs_rq utilization */
4223 add_positive(&cfs_rq->avg.util_avg, delta_avg);
4224 add_positive(&cfs_rq->avg.util_sum, delta_sum);
4225
4226 /* See update_cfs_rq_load_avg() */
4227 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4228 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4229 }
4230
4231 static inline void
update_tg_cfs_runnable(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4232 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4233 {
4234 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg;
4235 u32 new_sum, divider;
4236
4237 /* Nothing to update */
4238 if (!delta_avg)
4239 return;
4240
4241 /*
4242 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4243 * See ___update_load_avg() for details.
4244 */
4245 divider = get_pelt_divider(&cfs_rq->avg);
4246
4247 /* Set new sched_entity's runnable */
4248 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg;
4249 new_sum = se->avg.runnable_avg * divider;
4250 delta_sum = (long)new_sum - (long)se->avg.runnable_sum;
4251 se->avg.runnable_sum = new_sum;
4252
4253 /* Update parent cfs_rq runnable */
4254 add_positive(&cfs_rq->avg.runnable_avg, delta_avg);
4255 add_positive(&cfs_rq->avg.runnable_sum, delta_sum);
4256 /* See update_cfs_rq_load_avg() */
4257 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4258 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4259 }
4260
4261 static inline void
update_tg_cfs_load(struct cfs_rq * cfs_rq,struct sched_entity * se,struct cfs_rq * gcfs_rq)4262 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq)
4263 {
4264 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum;
4265 unsigned long load_avg;
4266 u64 load_sum = 0;
4267 s64 delta_sum;
4268 u32 divider;
4269
4270 if (!runnable_sum)
4271 return;
4272
4273 gcfs_rq->prop_runnable_sum = 0;
4274
4275 /*
4276 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4277 * See ___update_load_avg() for details.
4278 */
4279 divider = get_pelt_divider(&cfs_rq->avg);
4280
4281 if (runnable_sum >= 0) {
4282 /*
4283 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until
4284 * the CPU is saturated running == runnable.
4285 */
4286 runnable_sum += se->avg.load_sum;
4287 runnable_sum = min_t(long, runnable_sum, divider);
4288 } else {
4289 /*
4290 * Estimate the new unweighted runnable_sum of the gcfs_rq by
4291 * assuming all tasks are equally runnable.
4292 */
4293 if (scale_load_down(gcfs_rq->load.weight)) {
4294 load_sum = div_u64(gcfs_rq->avg.load_sum,
4295 scale_load_down(gcfs_rq->load.weight));
4296 }
4297
4298 /* But make sure to not inflate se's runnable */
4299 runnable_sum = min(se->avg.load_sum, load_sum);
4300 }
4301
4302 /*
4303 * runnable_sum can't be lower than running_sum
4304 * Rescale running sum to be in the same range as runnable sum
4305 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT]
4306 * runnable_sum is in [0 : LOAD_AVG_MAX]
4307 */
4308 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT;
4309 runnable_sum = max(runnable_sum, running_sum);
4310
4311 load_sum = se_weight(se) * runnable_sum;
4312 load_avg = div_u64(load_sum, divider);
4313
4314 delta_avg = load_avg - se->avg.load_avg;
4315 if (!delta_avg)
4316 return;
4317
4318 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum;
4319
4320 se->avg.load_sum = runnable_sum;
4321 se->avg.load_avg = load_avg;
4322 add_positive(&cfs_rq->avg.load_avg, delta_avg);
4323 add_positive(&cfs_rq->avg.load_sum, delta_sum);
4324 /* See update_cfs_rq_load_avg() */
4325 cfs_rq->avg.load_sum = max_t(u32, cfs_rq->avg.load_sum,
4326 cfs_rq->avg.load_avg * PELT_MIN_DIVIDER);
4327 }
4328
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4329 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum)
4330 {
4331 cfs_rq->propagate = 1;
4332 cfs_rq->prop_runnable_sum += runnable_sum;
4333 }
4334
4335 /* Update task and its cfs_rq load average */
propagate_entity_load_avg(struct sched_entity * se)4336 static inline int propagate_entity_load_avg(struct sched_entity *se)
4337 {
4338 struct cfs_rq *cfs_rq, *gcfs_rq;
4339
4340 if (entity_is_task(se))
4341 return 0;
4342
4343 gcfs_rq = group_cfs_rq(se);
4344 if (!gcfs_rq->propagate)
4345 return 0;
4346
4347 gcfs_rq->propagate = 0;
4348
4349 cfs_rq = cfs_rq_of(se);
4350
4351 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum);
4352
4353 update_tg_cfs_util(cfs_rq, se, gcfs_rq);
4354 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq);
4355 update_tg_cfs_load(cfs_rq, se, gcfs_rq);
4356
4357 trace_pelt_cfs_tp(cfs_rq);
4358 trace_pelt_se_tp(se);
4359
4360 return 1;
4361 }
4362
4363 /*
4364 * Check if we need to update the load and the utilization of a blocked
4365 * group_entity:
4366 */
skip_blocked_update(struct sched_entity * se)4367 static inline bool skip_blocked_update(struct sched_entity *se)
4368 {
4369 struct cfs_rq *gcfs_rq = group_cfs_rq(se);
4370
4371 /*
4372 * If sched_entity still have not zero load or utilization, we have to
4373 * decay it:
4374 */
4375 if (se->avg.load_avg || se->avg.util_avg)
4376 return false;
4377
4378 /*
4379 * If there is a pending propagation, we have to update the load and
4380 * the utilization of the sched_entity:
4381 */
4382 if (gcfs_rq->propagate)
4383 return false;
4384
4385 /*
4386 * Otherwise, the load and the utilization of the sched_entity is
4387 * already zero and there is no pending propagation, so it will be a
4388 * waste of time to try to decay it:
4389 */
4390 return true;
4391 }
4392
4393 #else /* CONFIG_FAIR_GROUP_SCHED */
4394
update_tg_load_avg(struct cfs_rq * cfs_rq)4395 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {}
4396
propagate_entity_load_avg(struct sched_entity * se)4397 static inline int propagate_entity_load_avg(struct sched_entity *se)
4398 {
4399 return 0;
4400 }
4401
add_tg_cfs_propagate(struct cfs_rq * cfs_rq,long runnable_sum)4402 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {}
4403
4404 #endif /* CONFIG_FAIR_GROUP_SCHED */
4405
4406 #ifdef CONFIG_NO_HZ_COMMON
migrate_se_pelt_lag(struct sched_entity * se)4407 static inline void migrate_se_pelt_lag(struct sched_entity *se)
4408 {
4409 u64 throttled = 0, now, lut;
4410 struct cfs_rq *cfs_rq;
4411 struct rq *rq;
4412 bool is_idle;
4413
4414 if (load_avg_is_decayed(&se->avg))
4415 return;
4416
4417 cfs_rq = cfs_rq_of(se);
4418 rq = rq_of(cfs_rq);
4419
4420 rcu_read_lock();
4421 is_idle = is_idle_task(rcu_dereference(rq->curr));
4422 rcu_read_unlock();
4423
4424 /*
4425 * The lag estimation comes with a cost we don't want to pay all the
4426 * time. Hence, limiting to the case where the source CPU is idle and
4427 * we know we are at the greatest risk to have an outdated clock.
4428 */
4429 if (!is_idle)
4430 return;
4431
4432 /*
4433 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where:
4434 *
4435 * last_update_time (the cfs_rq's last_update_time)
4436 * = cfs_rq_clock_pelt()@cfs_rq_idle
4437 * = rq_clock_pelt()@cfs_rq_idle
4438 * - cfs->throttled_clock_pelt_time@cfs_rq_idle
4439 *
4440 * cfs_idle_lag (delta between rq's update and cfs_rq's update)
4441 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle
4442 *
4443 * rq_idle_lag (delta between now and rq's update)
4444 * = sched_clock_cpu() - rq_clock()@rq_idle
4445 *
4446 * We can then write:
4447 *
4448 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time +
4449 * sched_clock_cpu() - rq_clock()@rq_idle
4450 * Where:
4451 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle
4452 * rq_clock()@rq_idle is rq->clock_idle
4453 * cfs->throttled_clock_pelt_time@cfs_rq_idle
4454 * is cfs_rq->throttled_pelt_idle
4455 */
4456
4457 #ifdef CONFIG_CFS_BANDWIDTH
4458 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle);
4459 /* The clock has been stopped for throttling */
4460 if (throttled == U64_MAX)
4461 return;
4462 #endif
4463 now = u64_u32_load(rq->clock_pelt_idle);
4464 /*
4465 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case
4466 * is observed the old clock_pelt_idle value and the new clock_idle,
4467 * which lead to an underestimation. The opposite would lead to an
4468 * overestimation.
4469 */
4470 smp_rmb();
4471 lut = cfs_rq_last_update_time(cfs_rq);
4472
4473 now -= throttled;
4474 if (now < lut)
4475 /*
4476 * cfs_rq->avg.last_update_time is more recent than our
4477 * estimation, let's use it.
4478 */
4479 now = lut;
4480 else
4481 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle);
4482
4483 __update_load_avg_blocked_se(now, se);
4484 }
4485 #else
migrate_se_pelt_lag(struct sched_entity * se)4486 static void migrate_se_pelt_lag(struct sched_entity *se) {}
4487 #endif
4488
4489 /**
4490 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages
4491 * @now: current time, as per cfs_rq_clock_pelt()
4492 * @cfs_rq: cfs_rq to update
4493 *
4494 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable)
4495 * avg. The immediate corollary is that all (fair) tasks must be attached.
4496 *
4497 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example.
4498 *
4499 * Return: true if the load decayed or we removed load.
4500 *
4501 * Since both these conditions indicate a changed cfs_rq->avg.load we should
4502 * call update_tg_load_avg() when this function returns true.
4503 */
4504 static inline int
update_cfs_rq_load_avg(u64 now,struct cfs_rq * cfs_rq)4505 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq)
4506 {
4507 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0;
4508 struct sched_avg *sa = &cfs_rq->avg;
4509 int decayed = 0;
4510
4511 if (cfs_rq->removed.nr) {
4512 unsigned long r;
4513 u32 divider = get_pelt_divider(&cfs_rq->avg);
4514
4515 raw_spin_lock(&cfs_rq->removed.lock);
4516 swap(cfs_rq->removed.util_avg, removed_util);
4517 swap(cfs_rq->removed.load_avg, removed_load);
4518 swap(cfs_rq->removed.runnable_avg, removed_runnable);
4519 cfs_rq->removed.nr = 0;
4520 raw_spin_unlock(&cfs_rq->removed.lock);
4521
4522 r = removed_load;
4523 sub_positive(&sa->load_avg, r);
4524 sub_positive(&sa->load_sum, r * divider);
4525 /* See sa->util_sum below */
4526 sa->load_sum = max_t(u32, sa->load_sum, sa->load_avg * PELT_MIN_DIVIDER);
4527
4528 r = removed_util;
4529 sub_positive(&sa->util_avg, r);
4530 sub_positive(&sa->util_sum, r * divider);
4531 /*
4532 * Because of rounding, se->util_sum might ends up being +1 more than
4533 * cfs->util_sum. Although this is not a problem by itself, detaching
4534 * a lot of tasks with the rounding problem between 2 updates of
4535 * util_avg (~1ms) can make cfs->util_sum becoming null whereas
4536 * cfs_util_avg is not.
4537 * Check that util_sum is still above its lower bound for the new
4538 * util_avg. Given that period_contrib might have moved since the last
4539 * sync, we are only sure that util_sum must be above or equal to
4540 * util_avg * minimum possible divider
4541 */
4542 sa->util_sum = max_t(u32, sa->util_sum, sa->util_avg * PELT_MIN_DIVIDER);
4543
4544 r = removed_runnable;
4545 sub_positive(&sa->runnable_avg, r);
4546 sub_positive(&sa->runnable_sum, r * divider);
4547 /* See sa->util_sum above */
4548 sa->runnable_sum = max_t(u32, sa->runnable_sum,
4549 sa->runnable_avg * PELT_MIN_DIVIDER);
4550
4551 /*
4552 * removed_runnable is the unweighted version of removed_load so we
4553 * can use it to estimate removed_load_sum.
4554 */
4555 add_tg_cfs_propagate(cfs_rq,
4556 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT);
4557
4558 decayed = 1;
4559 }
4560
4561 decayed |= __update_load_avg_cfs_rq(now, cfs_rq);
4562 u64_u32_store_copy(sa->last_update_time,
4563 cfs_rq->last_update_time_copy,
4564 sa->last_update_time);
4565 return decayed;
4566 }
4567
4568 /**
4569 * attach_entity_load_avg - attach this entity to its cfs_rq load avg
4570 * @cfs_rq: cfs_rq to attach to
4571 * @se: sched_entity to attach
4572 *
4573 * Must call update_cfs_rq_load_avg() before this, since we rely on
4574 * cfs_rq->avg.last_update_time being current.
4575 */
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4576 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4577 {
4578 /*
4579 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se.
4580 * See ___update_load_avg() for details.
4581 */
4582 u32 divider = get_pelt_divider(&cfs_rq->avg);
4583
4584 /*
4585 * When we attach the @se to the @cfs_rq, we must align the decay
4586 * window because without that, really weird and wonderful things can
4587 * happen.
4588 *
4589 * XXX illustrate
4590 */
4591 se->avg.last_update_time = cfs_rq->avg.last_update_time;
4592 se->avg.period_contrib = cfs_rq->avg.period_contrib;
4593
4594 /*
4595 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new
4596 * period_contrib. This isn't strictly correct, but since we're
4597 * entirely outside of the PELT hierarchy, nobody cares if we truncate
4598 * _sum a little.
4599 */
4600 se->avg.util_sum = se->avg.util_avg * divider;
4601
4602 se->avg.runnable_sum = se->avg.runnable_avg * divider;
4603
4604 se->avg.load_sum = se->avg.load_avg * divider;
4605 if (se_weight(se) < se->avg.load_sum)
4606 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se));
4607 else
4608 se->avg.load_sum = 1;
4609
4610 enqueue_load_avg(cfs_rq, se);
4611 cfs_rq->avg.util_avg += se->avg.util_avg;
4612 cfs_rq->avg.util_sum += se->avg.util_sum;
4613 cfs_rq->avg.runnable_avg += se->avg.runnable_avg;
4614 cfs_rq->avg.runnable_sum += se->avg.runnable_sum;
4615
4616 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum);
4617
4618 cfs_rq_util_change(cfs_rq, 0);
4619
4620 trace_pelt_cfs_tp(cfs_rq);
4621 }
4622
4623 /**
4624 * detach_entity_load_avg - detach this entity from its cfs_rq load avg
4625 * @cfs_rq: cfs_rq to detach from
4626 * @se: sched_entity to detach
4627 *
4628 * Must call update_cfs_rq_load_avg() before this, since we rely on
4629 * cfs_rq->avg.last_update_time being current.
4630 */
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4631 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se)
4632 {
4633 dequeue_load_avg(cfs_rq, se);
4634 sub_positive(&cfs_rq->avg.util_avg, se->avg.util_avg);
4635 sub_positive(&cfs_rq->avg.util_sum, se->avg.util_sum);
4636 /* See update_cfs_rq_load_avg() */
4637 cfs_rq->avg.util_sum = max_t(u32, cfs_rq->avg.util_sum,
4638 cfs_rq->avg.util_avg * PELT_MIN_DIVIDER);
4639
4640 sub_positive(&cfs_rq->avg.runnable_avg, se->avg.runnable_avg);
4641 sub_positive(&cfs_rq->avg.runnable_sum, se->avg.runnable_sum);
4642 /* See update_cfs_rq_load_avg() */
4643 cfs_rq->avg.runnable_sum = max_t(u32, cfs_rq->avg.runnable_sum,
4644 cfs_rq->avg.runnable_avg * PELT_MIN_DIVIDER);
4645
4646 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum);
4647
4648 cfs_rq_util_change(cfs_rq, 0);
4649
4650 trace_pelt_cfs_tp(cfs_rq);
4651 }
4652
4653 /*
4654 * Optional action to be done while updating the load average
4655 */
4656 #define UPDATE_TG 0x1
4657 #define SKIP_AGE_LOAD 0x2
4658 #define DO_ATTACH 0x4
4659 #define DO_DETACH 0x8
4660
4661 /* Update task and its cfs_rq load average */
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4662 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4663 {
4664 u64 now = cfs_rq_clock_pelt(cfs_rq);
4665 int decayed;
4666
4667 /*
4668 * Track task load average for carrying it to new CPU after migrated, and
4669 * track group sched_entity load average for task_h_load calc in migration
4670 */
4671 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD))
4672 __update_load_avg_se(now, cfs_rq, se);
4673
4674 decayed = update_cfs_rq_load_avg(now, cfs_rq);
4675 decayed |= propagate_entity_load_avg(se);
4676
4677 if (!se->avg.last_update_time && (flags & DO_ATTACH)) {
4678
4679 /*
4680 * DO_ATTACH means we're here from enqueue_entity().
4681 * !last_update_time means we've passed through
4682 * migrate_task_rq_fair() indicating we migrated.
4683 *
4684 * IOW we're enqueueing a task on a new CPU.
4685 */
4686 attach_entity_load_avg(cfs_rq, se);
4687 update_tg_load_avg(cfs_rq);
4688
4689 } else if (flags & DO_DETACH) {
4690 /*
4691 * DO_DETACH means we're here from dequeue_entity()
4692 * and we are migrating task out of the CPU.
4693 */
4694 detach_entity_load_avg(cfs_rq, se);
4695 update_tg_load_avg(cfs_rq);
4696 } else if (decayed) {
4697 cfs_rq_util_change(cfs_rq, 0);
4698
4699 if (flags & UPDATE_TG)
4700 update_tg_load_avg(cfs_rq);
4701 }
4702 }
4703
4704 /*
4705 * Synchronize entity load avg of dequeued entity without locking
4706 * the previous rq.
4707 */
sync_entity_load_avg(struct sched_entity * se)4708 static void sync_entity_load_avg(struct sched_entity *se)
4709 {
4710 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4711 u64 last_update_time;
4712
4713 last_update_time = cfs_rq_last_update_time(cfs_rq);
4714 __update_load_avg_blocked_se(last_update_time, se);
4715 }
4716
4717 /*
4718 * Task first catches up with cfs_rq, and then subtract
4719 * itself from the cfs_rq (task must be off the queue now).
4720 */
remove_entity_load_avg(struct sched_entity * se)4721 static void remove_entity_load_avg(struct sched_entity *se)
4722 {
4723 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4724 unsigned long flags;
4725
4726 /*
4727 * tasks cannot exit without having gone through wake_up_new_task() ->
4728 * enqueue_task_fair() which will have added things to the cfs_rq,
4729 * so we can remove unconditionally.
4730 */
4731
4732 sync_entity_load_avg(se);
4733
4734 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags);
4735 ++cfs_rq->removed.nr;
4736 cfs_rq->removed.util_avg += se->avg.util_avg;
4737 cfs_rq->removed.load_avg += se->avg.load_avg;
4738 cfs_rq->removed.runnable_avg += se->avg.runnable_avg;
4739 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags);
4740 }
4741
cfs_rq_runnable_avg(struct cfs_rq * cfs_rq)4742 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq)
4743 {
4744 return cfs_rq->avg.runnable_avg;
4745 }
4746
cfs_rq_load_avg(struct cfs_rq * cfs_rq)4747 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq)
4748 {
4749 return cfs_rq->avg.load_avg;
4750 }
4751
4752 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf);
4753
task_util(struct task_struct * p)4754 static inline unsigned long task_util(struct task_struct *p)
4755 {
4756 return READ_ONCE(p->se.avg.util_avg);
4757 }
4758
_task_util_est(struct task_struct * p)4759 static inline unsigned long _task_util_est(struct task_struct *p)
4760 {
4761 struct util_est ue = READ_ONCE(p->se.avg.util_est);
4762
4763 return max(ue.ewma, (ue.enqueued & ~UTIL_AVG_UNCHANGED));
4764 }
4765
task_util_est(struct task_struct * p)4766 static inline unsigned long task_util_est(struct task_struct *p)
4767 {
4768 return max(task_util(p), _task_util_est(p));
4769 }
4770
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4771 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
4772 struct task_struct *p)
4773 {
4774 unsigned int enqueued;
4775
4776 if (!sched_feat(UTIL_EST))
4777 return;
4778
4779 /* Update root cfs_rq's estimated utilization */
4780 enqueued = cfs_rq->avg.util_est.enqueued;
4781 enqueued += _task_util_est(p);
4782 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4783
4784 trace_sched_util_est_cfs_tp(cfs_rq);
4785 }
4786
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4787 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4788 struct task_struct *p)
4789 {
4790 unsigned int enqueued;
4791
4792 if (!sched_feat(UTIL_EST))
4793 return;
4794
4795 /* Update root cfs_rq's estimated utilization */
4796 enqueued = cfs_rq->avg.util_est.enqueued;
4797 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4798 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4799
4800 trace_sched_util_est_cfs_tp(cfs_rq);
4801 }
4802
4803 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4804
4805 /*
4806 * Check if a (signed) value is within a specified (unsigned) margin,
4807 * based on the observation that:
4808 *
4809 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4810 *
4811 * NOTE: this only works when value + margin < INT_MAX.
4812 */
within_margin(int value,int margin)4813 static inline bool within_margin(int value, int margin)
4814 {
4815 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4816 }
4817
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4818 static inline void util_est_update(struct cfs_rq *cfs_rq,
4819 struct task_struct *p,
4820 bool task_sleep)
4821 {
4822 long last_ewma_diff, last_enqueued_diff;
4823 struct util_est ue;
4824
4825 if (!sched_feat(UTIL_EST))
4826 return;
4827
4828 /*
4829 * Skip update of task's estimated utilization when the task has not
4830 * yet completed an activation, e.g. being migrated.
4831 */
4832 if (!task_sleep)
4833 return;
4834
4835 /*
4836 * If the PELT values haven't changed since enqueue time,
4837 * skip the util_est update.
4838 */
4839 ue = p->se.avg.util_est;
4840 if (ue.enqueued & UTIL_AVG_UNCHANGED)
4841 return;
4842
4843 last_enqueued_diff = ue.enqueued;
4844
4845 /*
4846 * Reset EWMA on utilization increases, the moving average is used only
4847 * to smooth utilization decreases.
4848 */
4849 ue.enqueued = task_util(p);
4850 if (sched_feat(UTIL_EST_FASTUP)) {
4851 if (ue.ewma < ue.enqueued) {
4852 ue.ewma = ue.enqueued;
4853 goto done;
4854 }
4855 }
4856
4857 /*
4858 * Skip update of task's estimated utilization when its members are
4859 * already ~1% close to its last activation value.
4860 */
4861 last_ewma_diff = ue.enqueued - ue.ewma;
4862 last_enqueued_diff -= ue.enqueued;
4863 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4864 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4865 goto done;
4866
4867 return;
4868 }
4869
4870 /*
4871 * To avoid overestimation of actual task utilization, skip updates if
4872 * we cannot grant there is idle time in this CPU.
4873 */
4874 if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4875 return;
4876
4877 /*
4878 * Update Task's estimated utilization
4879 *
4880 * When *p completes an activation we can consolidate another sample
4881 * of the task size. This is done by storing the current PELT value
4882 * as ue.enqueued and by using this value to update the Exponential
4883 * Weighted Moving Average (EWMA):
4884 *
4885 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4886 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4887 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4888 * = w * ( last_ewma_diff ) + ewma(t-1)
4889 * = w * (last_ewma_diff + ewma(t-1) / w)
4890 *
4891 * Where 'w' is the weight of new samples, which is configured to be
4892 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4893 */
4894 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4895 ue.ewma += last_ewma_diff;
4896 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4897 done:
4898 ue.enqueued |= UTIL_AVG_UNCHANGED;
4899 WRITE_ONCE(p->se.avg.util_est, ue);
4900
4901 trace_sched_util_est_se_tp(&p->se);
4902 }
4903
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)4904 static inline int util_fits_cpu(unsigned long util,
4905 unsigned long uclamp_min,
4906 unsigned long uclamp_max,
4907 int cpu)
4908 {
4909 unsigned long capacity_orig, capacity_orig_thermal;
4910 unsigned long capacity = capacity_of(cpu);
4911 bool fits, uclamp_max_fits;
4912
4913 /*
4914 * Check if the real util fits without any uclamp boost/cap applied.
4915 */
4916 fits = fits_capacity(util, capacity);
4917
4918 if (!uclamp_is_used())
4919 return fits;
4920
4921 /*
4922 * We must use capacity_orig_of() for comparing against uclamp_min and
4923 * uclamp_max. We only care about capacity pressure (by using
4924 * capacity_of()) for comparing against the real util.
4925 *
4926 * If a task is boosted to 1024 for example, we don't want a tiny
4927 * pressure to skew the check whether it fits a CPU or not.
4928 *
4929 * Similarly if a task is capped to capacity_orig_of(little_cpu), it
4930 * should fit a little cpu even if there's some pressure.
4931 *
4932 * Only exception is for thermal pressure since it has a direct impact
4933 * on available OPP of the system.
4934 *
4935 * We honour it for uclamp_min only as a drop in performance level
4936 * could result in not getting the requested minimum performance level.
4937 *
4938 * For uclamp_max, we can tolerate a drop in performance level as the
4939 * goal is to cap the task. So it's okay if it's getting less.
4940 */
4941 capacity_orig = capacity_orig_of(cpu);
4942 capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4943
4944 /*
4945 * We want to force a task to fit a cpu as implied by uclamp_max.
4946 * But we do have some corner cases to cater for..
4947 *
4948 *
4949 * C=z
4950 * | ___
4951 * | C=y | |
4952 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4953 * | C=x | | | |
4954 * | ___ | | | |
4955 * | | | | | | | (util somewhere in this region)
4956 * | | | | | | |
4957 * | | | | | | |
4958 * +----------------------------------------
4959 * cpu0 cpu1 cpu2
4960 *
4961 * In the above example if a task is capped to a specific performance
4962 * point, y, then when:
4963 *
4964 * * util = 80% of x then it does not fit on cpu0 and should migrate
4965 * to cpu1
4966 * * util = 80% of y then it is forced to fit on cpu1 to honour
4967 * uclamp_max request.
4968 *
4969 * which is what we're enforcing here. A task always fits if
4970 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4971 * the normal upmigration rules should withhold still.
4972 *
4973 * Only exception is when we are on max capacity, then we need to be
4974 * careful not to block overutilized state. This is so because:
4975 *
4976 * 1. There's no concept of capping at max_capacity! We can't go
4977 * beyond this performance level anyway.
4978 * 2. The system is being saturated when we're operating near
4979 * max capacity, it doesn't make sense to block overutilized.
4980 */
4981 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4982 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4983 fits = fits || uclamp_max_fits;
4984
4985 /*
4986 *
4987 * C=z
4988 * | ___ (region a, capped, util >= uclamp_max)
4989 * | C=y | |
4990 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4991 * | C=x | | | |
4992 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
4993 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
4994 * | | | | | | |
4995 * | | | | | | | (region c, boosted, util < uclamp_min)
4996 * +----------------------------------------
4997 * cpu0 cpu1 cpu2
4998 *
4999 * a) If util > uclamp_max, then we're capped, we don't care about
5000 * actual fitness value here. We only care if uclamp_max fits
5001 * capacity without taking margin/pressure into account.
5002 * See comment above.
5003 *
5004 * b) If uclamp_min <= util <= uclamp_max, then the normal
5005 * fits_capacity() rules apply. Except we need to ensure that we
5006 * enforce we remain within uclamp_max, see comment above.
5007 *
5008 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
5009 * need to take into account the boosted value fits the CPU without
5010 * taking margin/pressure into account.
5011 *
5012 * Cases (a) and (b) are handled in the 'fits' variable already. We
5013 * just need to consider an extra check for case (c) after ensuring we
5014 * handle the case uclamp_min > uclamp_max.
5015 */
5016 uclamp_min = min(uclamp_min, uclamp_max);
5017 if (fits && (util < uclamp_min) && (uclamp_min > capacity_orig_thermal))
5018 return -1;
5019
5020 return fits;
5021 }
5022
task_fits_cpu(struct task_struct * p,int cpu)5023 static inline int task_fits_cpu(struct task_struct *p, int cpu)
5024 {
5025 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN);
5026 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX);
5027 unsigned long util = task_util_est(p);
5028 /*
5029 * Return true only if the cpu fully fits the task requirements, which
5030 * include the utilization but also the performance hints.
5031 */
5032 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0);
5033 }
5034
update_misfit_status(struct task_struct * p,struct rq * rq)5035 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
5036 {
5037 if (!sched_asym_cpucap_active())
5038 return;
5039
5040 if (!p || p->nr_cpus_allowed == 1) {
5041 rq->misfit_task_load = 0;
5042 return;
5043 }
5044
5045 if (task_fits_cpu(p, cpu_of(rq))) {
5046 rq->misfit_task_load = 0;
5047 return;
5048 }
5049
5050 /*
5051 * Make sure that misfit_task_load will not be null even if
5052 * task_h_load() returns 0.
5053 */
5054 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
5055 }
5056
5057 #else /* CONFIG_SMP */
5058
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)5059 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
5060 {
5061 return !cfs_rq->nr_running;
5062 }
5063
5064 #define UPDATE_TG 0x0
5065 #define SKIP_AGE_LOAD 0x0
5066 #define DO_ATTACH 0x0
5067 #define DO_DETACH 0x0
5068
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int not_used1)5069 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
5070 {
5071 cfs_rq_util_change(cfs_rq, 0);
5072 }
5073
remove_entity_load_avg(struct sched_entity * se)5074 static inline void remove_entity_load_avg(struct sched_entity *se) {}
5075
5076 static inline void
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5077 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5078 static inline void
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)5079 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
5080
newidle_balance(struct rq * rq,struct rq_flags * rf)5081 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
5082 {
5083 return 0;
5084 }
5085
5086 static inline void
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)5087 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5088
5089 static inline void
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)5090 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
5091
5092 static inline void
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)5093 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
5094 bool task_sleep) {}
update_misfit_status(struct task_struct * p,struct rq * rq)5095 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
5096
5097 #endif /* CONFIG_SMP */
5098
5099 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5100 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5101 {
5102 u64 vslice, vruntime = avg_vruntime(cfs_rq);
5103 s64 lag = 0;
5104
5105 se->slice = sysctl_sched_base_slice;
5106 vslice = calc_delta_fair(se->slice, se);
5107
5108 /*
5109 * Due to how V is constructed as the weighted average of entities,
5110 * adding tasks with positive lag, or removing tasks with negative lag
5111 * will move 'time' backwards, this can screw around with the lag of
5112 * other tasks.
5113 *
5114 * EEVDF: placement strategy #1 / #2
5115 */
5116 if (sched_feat(PLACE_LAG) && cfs_rq->nr_running) {
5117 struct sched_entity *curr = cfs_rq->curr;
5118 unsigned long load;
5119
5120 lag = se->vlag;
5121
5122 /*
5123 * If we want to place a task and preserve lag, we have to
5124 * consider the effect of the new entity on the weighted
5125 * average and compensate for this, otherwise lag can quickly
5126 * evaporate.
5127 *
5128 * Lag is defined as:
5129 *
5130 * lag_i = S - s_i = w_i * (V - v_i)
5131 *
5132 * To avoid the 'w_i' term all over the place, we only track
5133 * the virtual lag:
5134 *
5135 * vl_i = V - v_i <=> v_i = V - vl_i
5136 *
5137 * And we take V to be the weighted average of all v:
5138 *
5139 * V = (\Sum w_j*v_j) / W
5140 *
5141 * Where W is: \Sum w_j
5142 *
5143 * Then, the weighted average after adding an entity with lag
5144 * vl_i is given by:
5145 *
5146 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i)
5147 * = (W*V + w_i*(V - vl_i)) / (W + w_i)
5148 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i)
5149 * = (V*(W + w_i) - w_i*l) / (W + w_i)
5150 * = V - w_i*vl_i / (W + w_i)
5151 *
5152 * And the actual lag after adding an entity with vl_i is:
5153 *
5154 * vl'_i = V' - v_i
5155 * = V - w_i*vl_i / (W + w_i) - (V - vl_i)
5156 * = vl_i - w_i*vl_i / (W + w_i)
5157 *
5158 * Which is strictly less than vl_i. So in order to preserve lag
5159 * we should inflate the lag before placement such that the
5160 * effective lag after placement comes out right.
5161 *
5162 * As such, invert the above relation for vl'_i to get the vl_i
5163 * we need to use such that the lag after placement is the lag
5164 * we computed before dequeue.
5165 *
5166 * vl'_i = vl_i - w_i*vl_i / (W + w_i)
5167 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i)
5168 *
5169 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i
5170 * = W*vl_i
5171 *
5172 * vl_i = (W + w_i)*vl'_i / W
5173 */
5174 load = cfs_rq->avg_load;
5175 if (curr && curr->on_rq)
5176 load += scale_load_down(curr->load.weight);
5177
5178 lag *= load + scale_load_down(se->load.weight);
5179 if (WARN_ON_ONCE(!load))
5180 load = 1;
5181 lag = div_s64(lag, load);
5182 }
5183
5184 se->vruntime = vruntime - lag;
5185
5186 /*
5187 * When joining the competition; the exisiting tasks will be,
5188 * on average, halfway through their slice, as such start tasks
5189 * off with half a slice to ease into the competition.
5190 */
5191 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL))
5192 vslice /= 2;
5193
5194 /*
5195 * EEVDF: vd_i = ve_i + r_i/w_i
5196 */
5197 se->deadline = se->vruntime + vslice;
5198 }
5199
5200 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
5201 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq);
5202
5203 static inline bool cfs_bandwidth_used(void);
5204
5205 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5206 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5207 {
5208 bool curr = cfs_rq->curr == se;
5209
5210 /*
5211 * If we're the current task, we must renormalise before calling
5212 * update_curr().
5213 */
5214 if (curr)
5215 place_entity(cfs_rq, se, flags);
5216
5217 update_curr(cfs_rq);
5218
5219 /*
5220 * When enqueuing a sched_entity, we must:
5221 * - Update loads to have both entity and cfs_rq synced with now.
5222 * - For group_entity, update its runnable_weight to reflect the new
5223 * h_nr_running of its group cfs_rq.
5224 * - For group_entity, update its weight to reflect the new share of
5225 * its group cfs_rq
5226 * - Add its new weight to cfs_rq->load.weight
5227 */
5228 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
5229 se_update_runnable(se);
5230 /*
5231 * XXX update_load_avg() above will have attached us to the pelt sum;
5232 * but update_cfs_group() here will re-adjust the weight and have to
5233 * undo/redo all that. Seems wasteful.
5234 */
5235 update_cfs_group(se);
5236
5237 /*
5238 * XXX now that the entity has been re-weighted, and it's lag adjusted,
5239 * we can place the entity.
5240 */
5241 if (!curr)
5242 place_entity(cfs_rq, se, flags);
5243
5244 account_entity_enqueue(cfs_rq, se);
5245
5246 /* Entity has migrated, no longer consider this task hot */
5247 if (flags & ENQUEUE_MIGRATED)
5248 se->exec_start = 0;
5249
5250 check_schedstat_required();
5251 update_stats_enqueue_fair(cfs_rq, se, flags);
5252 if (!curr)
5253 __enqueue_entity(cfs_rq, se);
5254 se->on_rq = 1;
5255
5256 if (cfs_rq->nr_running == 1) {
5257 check_enqueue_throttle(cfs_rq);
5258 if (!throttled_hierarchy(cfs_rq)) {
5259 list_add_leaf_cfs_rq(cfs_rq);
5260 } else {
5261 #ifdef CONFIG_CFS_BANDWIDTH
5262 struct rq *rq = rq_of(cfs_rq);
5263
5264 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock)
5265 cfs_rq->throttled_clock = rq_clock(rq);
5266 if (!cfs_rq->throttled_clock_self)
5267 cfs_rq->throttled_clock_self = rq_clock(rq);
5268 #endif
5269 }
5270 }
5271 }
5272
__clear_buddies_next(struct sched_entity * se)5273 static void __clear_buddies_next(struct sched_entity *se)
5274 {
5275 for_each_sched_entity(se) {
5276 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5277 if (cfs_rq->next != se)
5278 break;
5279
5280 cfs_rq->next = NULL;
5281 }
5282 }
5283
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)5284 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
5285 {
5286 if (cfs_rq->next == se)
5287 __clear_buddies_next(se);
5288 }
5289
5290 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5291
5292 static void
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)5293 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
5294 {
5295 int action = UPDATE_TG;
5296
5297 if (entity_is_task(se) && task_on_rq_migrating(task_of(se)))
5298 action |= DO_DETACH;
5299
5300 /*
5301 * Update run-time statistics of the 'current'.
5302 */
5303 update_curr(cfs_rq);
5304
5305 /*
5306 * When dequeuing a sched_entity, we must:
5307 * - Update loads to have both entity and cfs_rq synced with now.
5308 * - For group_entity, update its runnable_weight to reflect the new
5309 * h_nr_running of its group cfs_rq.
5310 * - Subtract its previous weight from cfs_rq->load.weight.
5311 * - For group entity, update its weight to reflect the new share
5312 * of its group cfs_rq.
5313 */
5314 update_load_avg(cfs_rq, se, action);
5315 se_update_runnable(se);
5316
5317 update_stats_dequeue_fair(cfs_rq, se, flags);
5318
5319 clear_buddies(cfs_rq, se);
5320
5321 update_entity_lag(cfs_rq, se);
5322 if (se != cfs_rq->curr)
5323 __dequeue_entity(cfs_rq, se);
5324 se->on_rq = 0;
5325 account_entity_dequeue(cfs_rq, se);
5326
5327 /* return excess runtime on last dequeue */
5328 return_cfs_rq_runtime(cfs_rq);
5329
5330 update_cfs_group(se);
5331
5332 /*
5333 * Now advance min_vruntime if @se was the entity holding it back,
5334 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
5335 * put back on, and if we advance min_vruntime, we'll be placed back
5336 * further than we started -- ie. we'll be penalized.
5337 */
5338 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
5339 update_min_vruntime(cfs_rq);
5340
5341 if (cfs_rq->nr_running == 0)
5342 update_idle_cfs_rq_clock_pelt(cfs_rq);
5343 }
5344
5345 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)5346 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
5347 {
5348 clear_buddies(cfs_rq, se);
5349
5350 /* 'current' is not kept within the tree. */
5351 if (se->on_rq) {
5352 /*
5353 * Any task has to be enqueued before it get to execute on
5354 * a CPU. So account for the time it spent waiting on the
5355 * runqueue.
5356 */
5357 update_stats_wait_end_fair(cfs_rq, se);
5358 __dequeue_entity(cfs_rq, se);
5359 update_load_avg(cfs_rq, se, UPDATE_TG);
5360 /*
5361 * HACK, stash a copy of deadline at the point of pick in vlag,
5362 * which isn't used until dequeue.
5363 */
5364 se->vlag = se->deadline;
5365 }
5366
5367 update_stats_curr_start(cfs_rq, se);
5368 cfs_rq->curr = se;
5369
5370 /*
5371 * Track our maximum slice length, if the CPU's load is at
5372 * least twice that of our own weight (i.e. dont track it
5373 * when there are only lesser-weight tasks around):
5374 */
5375 if (schedstat_enabled() &&
5376 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
5377 struct sched_statistics *stats;
5378
5379 stats = __schedstats_from_se(se);
5380 __schedstat_set(stats->slice_max,
5381 max((u64)stats->slice_max,
5382 se->sum_exec_runtime - se->prev_sum_exec_runtime));
5383 }
5384
5385 se->prev_sum_exec_runtime = se->sum_exec_runtime;
5386 }
5387
5388 static int
5389 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
5390
5391 /*
5392 * Pick the next process, keeping these things in mind, in this order:
5393 * 1) keep things fair between processes/task groups
5394 * 2) pick the "next" process, since someone really wants that to run
5395 * 3) pick the "last" process, for cache locality
5396 * 4) do not run the "skip" process, if something else is available
5397 */
5398 static struct sched_entity *
pick_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * curr)5399 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
5400 {
5401 /*
5402 * Enabling NEXT_BUDDY will affect latency but not fairness.
5403 */
5404 if (sched_feat(NEXT_BUDDY) &&
5405 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next))
5406 return cfs_rq->next;
5407
5408 return pick_eevdf(cfs_rq);
5409 }
5410
5411 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
5412
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)5413 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
5414 {
5415 /*
5416 * If still on the runqueue then deactivate_task()
5417 * was not called and update_curr() has to be done:
5418 */
5419 if (prev->on_rq)
5420 update_curr(cfs_rq);
5421
5422 /* throttle cfs_rqs exceeding runtime */
5423 check_cfs_rq_runtime(cfs_rq);
5424
5425 if (prev->on_rq) {
5426 update_stats_wait_start_fair(cfs_rq, prev);
5427 /* Put 'current' back into the tree. */
5428 __enqueue_entity(cfs_rq, prev);
5429 /* in !on_rq case, update occurred at dequeue */
5430 update_load_avg(cfs_rq, prev, 0);
5431 }
5432 cfs_rq->curr = NULL;
5433 }
5434
5435 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)5436 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
5437 {
5438 /*
5439 * Update run-time statistics of the 'current'.
5440 */
5441 update_curr(cfs_rq);
5442
5443 /*
5444 * Ensure that runnable average is periodically updated.
5445 */
5446 update_load_avg(cfs_rq, curr, UPDATE_TG);
5447 update_cfs_group(curr);
5448
5449 #ifdef CONFIG_SCHED_HRTICK
5450 /*
5451 * queued ticks are scheduled to match the slice, so don't bother
5452 * validating it and just reschedule.
5453 */
5454 if (queued) {
5455 resched_curr(rq_of(cfs_rq));
5456 return;
5457 }
5458 /*
5459 * don't let the period tick interfere with the hrtick preemption
5460 */
5461 if (!sched_feat(DOUBLE_TICK) &&
5462 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
5463 return;
5464 #endif
5465 }
5466
5467
5468 /**************************************************
5469 * CFS bandwidth control machinery
5470 */
5471
5472 #ifdef CONFIG_CFS_BANDWIDTH
5473
5474 #ifdef CONFIG_JUMP_LABEL
5475 static struct static_key __cfs_bandwidth_used;
5476
cfs_bandwidth_used(void)5477 static inline bool cfs_bandwidth_used(void)
5478 {
5479 return static_key_false(&__cfs_bandwidth_used);
5480 }
5481
cfs_bandwidth_usage_inc(void)5482 void cfs_bandwidth_usage_inc(void)
5483 {
5484 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
5485 }
5486
cfs_bandwidth_usage_dec(void)5487 void cfs_bandwidth_usage_dec(void)
5488 {
5489 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
5490 }
5491 #else /* CONFIG_JUMP_LABEL */
cfs_bandwidth_used(void)5492 static bool cfs_bandwidth_used(void)
5493 {
5494 return true;
5495 }
5496
cfs_bandwidth_usage_inc(void)5497 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)5498 void cfs_bandwidth_usage_dec(void) {}
5499 #endif /* CONFIG_JUMP_LABEL */
5500
5501 /*
5502 * default period for cfs group bandwidth.
5503 * default: 0.1s, units: nanoseconds
5504 */
default_cfs_period(void)5505 static inline u64 default_cfs_period(void)
5506 {
5507 return 100000000ULL;
5508 }
5509
sched_cfs_bandwidth_slice(void)5510 static inline u64 sched_cfs_bandwidth_slice(void)
5511 {
5512 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
5513 }
5514
5515 /*
5516 * Replenish runtime according to assigned quota. We use sched_clock_cpu
5517 * directly instead of rq->clock to avoid adding additional synchronization
5518 * around rq->lock.
5519 *
5520 * requires cfs_b->lock
5521 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)5522 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
5523 {
5524 s64 runtime;
5525
5526 if (unlikely(cfs_b->quota == RUNTIME_INF))
5527 return;
5528
5529 cfs_b->runtime += cfs_b->quota;
5530 runtime = cfs_b->runtime_snap - cfs_b->runtime;
5531 if (runtime > 0) {
5532 cfs_b->burst_time += runtime;
5533 cfs_b->nr_burst++;
5534 }
5535
5536 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst);
5537 cfs_b->runtime_snap = cfs_b->runtime;
5538 }
5539
tg_cfs_bandwidth(struct task_group * tg)5540 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5541 {
5542 return &tg->cfs_bandwidth;
5543 }
5544
5545 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)5546 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
5547 struct cfs_rq *cfs_rq, u64 target_runtime)
5548 {
5549 u64 min_amount, amount = 0;
5550
5551 lockdep_assert_held(&cfs_b->lock);
5552
5553 /* note: this is a positive sum as runtime_remaining <= 0 */
5554 min_amount = target_runtime - cfs_rq->runtime_remaining;
5555
5556 if (cfs_b->quota == RUNTIME_INF)
5557 amount = min_amount;
5558 else {
5559 start_cfs_bandwidth(cfs_b);
5560
5561 if (cfs_b->runtime > 0) {
5562 amount = min(cfs_b->runtime, min_amount);
5563 cfs_b->runtime -= amount;
5564 cfs_b->idle = 0;
5565 }
5566 }
5567
5568 cfs_rq->runtime_remaining += amount;
5569
5570 return cfs_rq->runtime_remaining > 0;
5571 }
5572
5573 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)5574 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5575 {
5576 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5577 int ret;
5578
5579 raw_spin_lock(&cfs_b->lock);
5580 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
5581 raw_spin_unlock(&cfs_b->lock);
5582
5583 return ret;
5584 }
5585
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5586 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5587 {
5588 /* dock delta_exec before expiring quota (as it could span periods) */
5589 cfs_rq->runtime_remaining -= delta_exec;
5590
5591 if (likely(cfs_rq->runtime_remaining > 0))
5592 return;
5593
5594 if (cfs_rq->throttled)
5595 return;
5596 /*
5597 * if we're unable to extend our runtime we resched so that the active
5598 * hierarchy can be throttled
5599 */
5600 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
5601 resched_curr(rq_of(cfs_rq));
5602 }
5603
5604 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5605 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
5606 {
5607 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
5608 return;
5609
5610 __account_cfs_rq_runtime(cfs_rq, delta_exec);
5611 }
5612
cfs_rq_throttled(struct cfs_rq * cfs_rq)5613 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5614 {
5615 return cfs_bandwidth_used() && cfs_rq->throttled;
5616 }
5617
5618 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)5619 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5620 {
5621 return cfs_bandwidth_used() && cfs_rq->throttle_count;
5622 }
5623
5624 /*
5625 * Ensure that neither of the group entities corresponding to src_cpu or
5626 * dest_cpu are members of a throttled hierarchy when performing group
5627 * load-balance operations.
5628 */
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)5629 static inline int throttled_lb_pair(struct task_group *tg,
5630 int src_cpu, int dest_cpu)
5631 {
5632 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
5633
5634 src_cfs_rq = tg->cfs_rq[src_cpu];
5635 dest_cfs_rq = tg->cfs_rq[dest_cpu];
5636
5637 return throttled_hierarchy(src_cfs_rq) ||
5638 throttled_hierarchy(dest_cfs_rq);
5639 }
5640
tg_unthrottle_up(struct task_group * tg,void * data)5641 static int tg_unthrottle_up(struct task_group *tg, void *data)
5642 {
5643 struct rq *rq = data;
5644 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5645
5646 cfs_rq->throttle_count--;
5647 if (!cfs_rq->throttle_count) {
5648 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
5649 cfs_rq->throttled_clock_pelt;
5650
5651 /* Add cfs_rq with load or one or more already running entities to the list */
5652 if (!cfs_rq_is_decayed(cfs_rq))
5653 list_add_leaf_cfs_rq(cfs_rq);
5654
5655 if (cfs_rq->throttled_clock_self) {
5656 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self;
5657
5658 cfs_rq->throttled_clock_self = 0;
5659
5660 if (SCHED_WARN_ON((s64)delta < 0))
5661 delta = 0;
5662
5663 cfs_rq->throttled_clock_self_time += delta;
5664 }
5665 }
5666
5667 return 0;
5668 }
5669
tg_throttle_down(struct task_group * tg,void * data)5670 static int tg_throttle_down(struct task_group *tg, void *data)
5671 {
5672 struct rq *rq = data;
5673 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5674
5675 /* group is entering throttled state, stop time */
5676 if (!cfs_rq->throttle_count) {
5677 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
5678 list_del_leaf_cfs_rq(cfs_rq);
5679
5680 SCHED_WARN_ON(cfs_rq->throttled_clock_self);
5681 if (cfs_rq->nr_running)
5682 cfs_rq->throttled_clock_self = rq_clock(rq);
5683 }
5684 cfs_rq->throttle_count++;
5685
5686 return 0;
5687 }
5688
throttle_cfs_rq(struct cfs_rq * cfs_rq)5689 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
5690 {
5691 struct rq *rq = rq_of(cfs_rq);
5692 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5693 struct sched_entity *se;
5694 long task_delta, idle_task_delta, dequeue = 1;
5695
5696 raw_spin_lock(&cfs_b->lock);
5697 /* This will start the period timer if necessary */
5698 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
5699 /*
5700 * We have raced with bandwidth becoming available, and if we
5701 * actually throttled the timer might not unthrottle us for an
5702 * entire period. We additionally needed to make sure that any
5703 * subsequent check_cfs_rq_runtime calls agree not to throttle
5704 * us, as we may commit to do cfs put_prev+pick_next, so we ask
5705 * for 1ns of runtime rather than just check cfs_b.
5706 */
5707 dequeue = 0;
5708 } else {
5709 list_add_tail_rcu(&cfs_rq->throttled_list,
5710 &cfs_b->throttled_cfs_rq);
5711 }
5712 raw_spin_unlock(&cfs_b->lock);
5713
5714 if (!dequeue)
5715 return false; /* Throttle no longer required. */
5716
5717 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5718
5719 /* freeze hierarchy runnable averages while throttled */
5720 rcu_read_lock();
5721 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5722 rcu_read_unlock();
5723
5724 task_delta = cfs_rq->h_nr_running;
5725 idle_task_delta = cfs_rq->idle_h_nr_running;
5726 for_each_sched_entity(se) {
5727 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5728 /* throttled entity or throttle-on-deactivate */
5729 if (!se->on_rq)
5730 goto done;
5731
5732 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5733
5734 if (cfs_rq_is_idle(group_cfs_rq(se)))
5735 idle_task_delta = cfs_rq->h_nr_running;
5736
5737 qcfs_rq->h_nr_running -= task_delta;
5738 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5739
5740 if (qcfs_rq->load.weight) {
5741 /* Avoid re-evaluating load for this entity: */
5742 se = parent_entity(se);
5743 break;
5744 }
5745 }
5746
5747 for_each_sched_entity(se) {
5748 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5749 /* throttled entity or throttle-on-deactivate */
5750 if (!se->on_rq)
5751 goto done;
5752
5753 update_load_avg(qcfs_rq, se, 0);
5754 se_update_runnable(se);
5755
5756 if (cfs_rq_is_idle(group_cfs_rq(se)))
5757 idle_task_delta = cfs_rq->h_nr_running;
5758
5759 qcfs_rq->h_nr_running -= task_delta;
5760 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5761 }
5762
5763 /* At this point se is NULL and we are at root level*/
5764 sub_nr_running(rq, task_delta);
5765
5766 done:
5767 /*
5768 * Note: distribution will already see us throttled via the
5769 * throttled-list. rq->lock protects completion.
5770 */
5771 cfs_rq->throttled = 1;
5772 SCHED_WARN_ON(cfs_rq->throttled_clock);
5773 if (cfs_rq->nr_running)
5774 cfs_rq->throttled_clock = rq_clock(rq);
5775 return true;
5776 }
5777
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)5778 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5779 {
5780 struct rq *rq = rq_of(cfs_rq);
5781 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5782 struct sched_entity *se;
5783 long task_delta, idle_task_delta;
5784
5785 se = cfs_rq->tg->se[cpu_of(rq)];
5786
5787 cfs_rq->throttled = 0;
5788
5789 update_rq_clock(rq);
5790
5791 raw_spin_lock(&cfs_b->lock);
5792 if (cfs_rq->throttled_clock) {
5793 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5794 cfs_rq->throttled_clock = 0;
5795 }
5796 list_del_rcu(&cfs_rq->throttled_list);
5797 raw_spin_unlock(&cfs_b->lock);
5798
5799 /* update hierarchical throttle state */
5800 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5801
5802 if (!cfs_rq->load.weight) {
5803 if (!cfs_rq->on_list)
5804 return;
5805 /*
5806 * Nothing to run but something to decay (on_list)?
5807 * Complete the branch.
5808 */
5809 for_each_sched_entity(se) {
5810 if (list_add_leaf_cfs_rq(cfs_rq_of(se)))
5811 break;
5812 }
5813 goto unthrottle_throttle;
5814 }
5815
5816 task_delta = cfs_rq->h_nr_running;
5817 idle_task_delta = cfs_rq->idle_h_nr_running;
5818 for_each_sched_entity(se) {
5819 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5820
5821 if (se->on_rq)
5822 break;
5823 enqueue_entity(qcfs_rq, se, ENQUEUE_WAKEUP);
5824
5825 if (cfs_rq_is_idle(group_cfs_rq(se)))
5826 idle_task_delta = cfs_rq->h_nr_running;
5827
5828 qcfs_rq->h_nr_running += task_delta;
5829 qcfs_rq->idle_h_nr_running += idle_task_delta;
5830
5831 /* end evaluation on encountering a throttled cfs_rq */
5832 if (cfs_rq_throttled(qcfs_rq))
5833 goto unthrottle_throttle;
5834 }
5835
5836 for_each_sched_entity(se) {
5837 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5838
5839 update_load_avg(qcfs_rq, se, UPDATE_TG);
5840 se_update_runnable(se);
5841
5842 if (cfs_rq_is_idle(group_cfs_rq(se)))
5843 idle_task_delta = cfs_rq->h_nr_running;
5844
5845 qcfs_rq->h_nr_running += task_delta;
5846 qcfs_rq->idle_h_nr_running += idle_task_delta;
5847
5848 /* end evaluation on encountering a throttled cfs_rq */
5849 if (cfs_rq_throttled(qcfs_rq))
5850 goto unthrottle_throttle;
5851 }
5852
5853 /* At this point se is NULL and we are at root level*/
5854 add_nr_running(rq, task_delta);
5855
5856 unthrottle_throttle:
5857 assert_list_leaf_cfs_rq(rq);
5858
5859 /* Determine whether we need to wake up potentially idle CPU: */
5860 if (rq->curr == rq->idle && rq->cfs.nr_running)
5861 resched_curr(rq);
5862 }
5863
5864 #ifdef CONFIG_SMP
__cfsb_csd_unthrottle(void * arg)5865 static void __cfsb_csd_unthrottle(void *arg)
5866 {
5867 struct cfs_rq *cursor, *tmp;
5868 struct rq *rq = arg;
5869 struct rq_flags rf;
5870
5871 rq_lock(rq, &rf);
5872
5873 /*
5874 * Iterating over the list can trigger several call to
5875 * update_rq_clock() in unthrottle_cfs_rq().
5876 * Do it once and skip the potential next ones.
5877 */
5878 update_rq_clock(rq);
5879 rq_clock_start_loop_update(rq);
5880
5881 /*
5882 * Since we hold rq lock we're safe from concurrent manipulation of
5883 * the CSD list. However, this RCU critical section annotates the
5884 * fact that we pair with sched_free_group_rcu(), so that we cannot
5885 * race with group being freed in the window between removing it
5886 * from the list and advancing to the next entry in the list.
5887 */
5888 rcu_read_lock();
5889
5890 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list,
5891 throttled_csd_list) {
5892 list_del_init(&cursor->throttled_csd_list);
5893
5894 if (cfs_rq_throttled(cursor))
5895 unthrottle_cfs_rq(cursor);
5896 }
5897
5898 rcu_read_unlock();
5899
5900 rq_clock_stop_loop_update(rq);
5901 rq_unlock(rq, &rf);
5902 }
5903
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)5904 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5905 {
5906 struct rq *rq = rq_of(cfs_rq);
5907 bool first;
5908
5909 if (rq == this_rq()) {
5910 unthrottle_cfs_rq(cfs_rq);
5911 return;
5912 }
5913
5914 /* Already enqueued */
5915 if (SCHED_WARN_ON(!list_empty(&cfs_rq->throttled_csd_list)))
5916 return;
5917
5918 first = list_empty(&rq->cfsb_csd_list);
5919 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list);
5920 if (first)
5921 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd);
5922 }
5923 #else
__unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)5924 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5925 {
5926 unthrottle_cfs_rq(cfs_rq);
5927 }
5928 #endif
5929
unthrottle_cfs_rq_async(struct cfs_rq * cfs_rq)5930 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq)
5931 {
5932 lockdep_assert_rq_held(rq_of(cfs_rq));
5933
5934 if (SCHED_WARN_ON(!cfs_rq_throttled(cfs_rq) ||
5935 cfs_rq->runtime_remaining <= 0))
5936 return;
5937
5938 __unthrottle_cfs_rq_async(cfs_rq);
5939 }
5940
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)5941 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5942 {
5943 struct cfs_rq *local_unthrottle = NULL;
5944 int this_cpu = smp_processor_id();
5945 u64 runtime, remaining = 1;
5946 bool throttled = false;
5947 struct cfs_rq *cfs_rq;
5948 struct rq_flags rf;
5949 struct rq *rq;
5950
5951 rcu_read_lock();
5952 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5953 throttled_list) {
5954 rq = rq_of(cfs_rq);
5955
5956 if (!remaining) {
5957 throttled = true;
5958 break;
5959 }
5960
5961 rq_lock_irqsave(rq, &rf);
5962 if (!cfs_rq_throttled(cfs_rq))
5963 goto next;
5964
5965 #ifdef CONFIG_SMP
5966 /* Already queued for async unthrottle */
5967 if (!list_empty(&cfs_rq->throttled_csd_list))
5968 goto next;
5969 #endif
5970
5971 /* By the above checks, this should never be true */
5972 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5973
5974 raw_spin_lock(&cfs_b->lock);
5975 runtime = -cfs_rq->runtime_remaining + 1;
5976 if (runtime > cfs_b->runtime)
5977 runtime = cfs_b->runtime;
5978 cfs_b->runtime -= runtime;
5979 remaining = cfs_b->runtime;
5980 raw_spin_unlock(&cfs_b->lock);
5981
5982 cfs_rq->runtime_remaining += runtime;
5983
5984 /* we check whether we're throttled above */
5985 if (cfs_rq->runtime_remaining > 0) {
5986 if (cpu_of(rq) != this_cpu ||
5987 SCHED_WARN_ON(local_unthrottle))
5988 unthrottle_cfs_rq_async(cfs_rq);
5989 else
5990 local_unthrottle = cfs_rq;
5991 } else {
5992 throttled = true;
5993 }
5994
5995 next:
5996 rq_unlock_irqrestore(rq, &rf);
5997 }
5998 rcu_read_unlock();
5999
6000 if (local_unthrottle) {
6001 rq = cpu_rq(this_cpu);
6002 rq_lock_irqsave(rq, &rf);
6003 if (cfs_rq_throttled(local_unthrottle))
6004 unthrottle_cfs_rq(local_unthrottle);
6005 rq_unlock_irqrestore(rq, &rf);
6006 }
6007
6008 return throttled;
6009 }
6010
6011 /*
6012 * Responsible for refilling a task_group's bandwidth and unthrottling its
6013 * cfs_rqs as appropriate. If there has been no activity within the last
6014 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
6015 * used to track this state.
6016 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)6017 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
6018 {
6019 int throttled;
6020
6021 /* no need to continue the timer with no bandwidth constraint */
6022 if (cfs_b->quota == RUNTIME_INF)
6023 goto out_deactivate;
6024
6025 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
6026 cfs_b->nr_periods += overrun;
6027
6028 /* Refill extra burst quota even if cfs_b->idle */
6029 __refill_cfs_bandwidth_runtime(cfs_b);
6030
6031 /*
6032 * idle depends on !throttled (for the case of a large deficit), and if
6033 * we're going inactive then everything else can be deferred
6034 */
6035 if (cfs_b->idle && !throttled)
6036 goto out_deactivate;
6037
6038 if (!throttled) {
6039 /* mark as potentially idle for the upcoming period */
6040 cfs_b->idle = 1;
6041 return 0;
6042 }
6043
6044 /* account preceding periods in which throttling occurred */
6045 cfs_b->nr_throttled += overrun;
6046
6047 /*
6048 * This check is repeated as we release cfs_b->lock while we unthrottle.
6049 */
6050 while (throttled && cfs_b->runtime > 0) {
6051 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6052 /* we can't nest cfs_b->lock while distributing bandwidth */
6053 throttled = distribute_cfs_runtime(cfs_b);
6054 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6055 }
6056
6057 /*
6058 * While we are ensured activity in the period following an
6059 * unthrottle, this also covers the case in which the new bandwidth is
6060 * insufficient to cover the existing bandwidth deficit. (Forcing the
6061 * timer to remain active while there are any throttled entities.)
6062 */
6063 cfs_b->idle = 0;
6064
6065 return 0;
6066
6067 out_deactivate:
6068 return 1;
6069 }
6070
6071 /* a cfs_rq won't donate quota below this amount */
6072 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
6073 /* minimum remaining period time to redistribute slack quota */
6074 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
6075 /* how long we wait to gather additional slack before distributing */
6076 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
6077
6078 /*
6079 * Are we near the end of the current quota period?
6080 *
6081 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
6082 * hrtimer base being cleared by hrtimer_start. In the case of
6083 * migrate_hrtimers, base is never cleared, so we are fine.
6084 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)6085 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
6086 {
6087 struct hrtimer *refresh_timer = &cfs_b->period_timer;
6088 s64 remaining;
6089
6090 /* if the call-back is running a quota refresh is already occurring */
6091 if (hrtimer_callback_running(refresh_timer))
6092 return 1;
6093
6094 /* is a quota refresh about to occur? */
6095 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
6096 if (remaining < (s64)min_expire)
6097 return 1;
6098
6099 return 0;
6100 }
6101
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)6102 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
6103 {
6104 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
6105
6106 /* if there's a quota refresh soon don't bother with slack */
6107 if (runtime_refresh_within(cfs_b, min_left))
6108 return;
6109
6110 /* don't push forwards an existing deferred unthrottle */
6111 if (cfs_b->slack_started)
6112 return;
6113 cfs_b->slack_started = true;
6114
6115 hrtimer_start(&cfs_b->slack_timer,
6116 ns_to_ktime(cfs_bandwidth_slack_period),
6117 HRTIMER_MODE_REL);
6118 }
6119
6120 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6121 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6122 {
6123 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
6124 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
6125
6126 if (slack_runtime <= 0)
6127 return;
6128
6129 raw_spin_lock(&cfs_b->lock);
6130 if (cfs_b->quota != RUNTIME_INF) {
6131 cfs_b->runtime += slack_runtime;
6132
6133 /* we are under rq->lock, defer unthrottling using a timer */
6134 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
6135 !list_empty(&cfs_b->throttled_cfs_rq))
6136 start_cfs_slack_bandwidth(cfs_b);
6137 }
6138 raw_spin_unlock(&cfs_b->lock);
6139
6140 /* even if it's not valid for return we don't want to try again */
6141 cfs_rq->runtime_remaining -= slack_runtime;
6142 }
6143
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6144 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6145 {
6146 if (!cfs_bandwidth_used())
6147 return;
6148
6149 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
6150 return;
6151
6152 __return_cfs_rq_runtime(cfs_rq);
6153 }
6154
6155 /*
6156 * This is done with a timer (instead of inline with bandwidth return) since
6157 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
6158 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)6159 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
6160 {
6161 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
6162 unsigned long flags;
6163
6164 /* confirm we're still not at a refresh boundary */
6165 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6166 cfs_b->slack_started = false;
6167
6168 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
6169 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6170 return;
6171 }
6172
6173 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
6174 runtime = cfs_b->runtime;
6175
6176 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6177
6178 if (!runtime)
6179 return;
6180
6181 distribute_cfs_runtime(cfs_b);
6182 }
6183
6184 /*
6185 * When a group wakes up we want to make sure that its quota is not already
6186 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
6187 * runtime as update_curr() throttling can not trigger until it's on-rq.
6188 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)6189 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
6190 {
6191 if (!cfs_bandwidth_used())
6192 return;
6193
6194 /* an active group must be handled by the update_curr()->put() path */
6195 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
6196 return;
6197
6198 /* ensure the group is not already throttled */
6199 if (cfs_rq_throttled(cfs_rq))
6200 return;
6201
6202 /* update runtime allocation */
6203 account_cfs_rq_runtime(cfs_rq, 0);
6204 if (cfs_rq->runtime_remaining <= 0)
6205 throttle_cfs_rq(cfs_rq);
6206 }
6207
sync_throttle(struct task_group * tg,int cpu)6208 static void sync_throttle(struct task_group *tg, int cpu)
6209 {
6210 struct cfs_rq *pcfs_rq, *cfs_rq;
6211
6212 if (!cfs_bandwidth_used())
6213 return;
6214
6215 if (!tg->parent)
6216 return;
6217
6218 cfs_rq = tg->cfs_rq[cpu];
6219 pcfs_rq = tg->parent->cfs_rq[cpu];
6220
6221 cfs_rq->throttle_count = pcfs_rq->throttle_count;
6222 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
6223 }
6224
6225 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6226 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6227 {
6228 if (!cfs_bandwidth_used())
6229 return false;
6230
6231 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
6232 return false;
6233
6234 /*
6235 * it's possible for a throttled entity to be forced into a running
6236 * state (e.g. set_curr_task), in this case we're finished.
6237 */
6238 if (cfs_rq_throttled(cfs_rq))
6239 return true;
6240
6241 return throttle_cfs_rq(cfs_rq);
6242 }
6243
sched_cfs_slack_timer(struct hrtimer * timer)6244 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
6245 {
6246 struct cfs_bandwidth *cfs_b =
6247 container_of(timer, struct cfs_bandwidth, slack_timer);
6248
6249 do_sched_cfs_slack_timer(cfs_b);
6250
6251 return HRTIMER_NORESTART;
6252 }
6253
6254 extern const u64 max_cfs_quota_period;
6255
sched_cfs_period_timer(struct hrtimer * timer)6256 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
6257 {
6258 struct cfs_bandwidth *cfs_b =
6259 container_of(timer, struct cfs_bandwidth, period_timer);
6260 unsigned long flags;
6261 int overrun;
6262 int idle = 0;
6263 int count = 0;
6264
6265 raw_spin_lock_irqsave(&cfs_b->lock, flags);
6266 for (;;) {
6267 overrun = hrtimer_forward_now(timer, cfs_b->period);
6268 if (!overrun)
6269 break;
6270
6271 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
6272
6273 if (++count > 3) {
6274 u64 new, old = ktime_to_ns(cfs_b->period);
6275
6276 /*
6277 * Grow period by a factor of 2 to avoid losing precision.
6278 * Precision loss in the quota/period ratio can cause __cfs_schedulable
6279 * to fail.
6280 */
6281 new = old * 2;
6282 if (new < max_cfs_quota_period) {
6283 cfs_b->period = ns_to_ktime(new);
6284 cfs_b->quota *= 2;
6285 cfs_b->burst *= 2;
6286
6287 pr_warn_ratelimited(
6288 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6289 smp_processor_id(),
6290 div_u64(new, NSEC_PER_USEC),
6291 div_u64(cfs_b->quota, NSEC_PER_USEC));
6292 } else {
6293 pr_warn_ratelimited(
6294 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
6295 smp_processor_id(),
6296 div_u64(old, NSEC_PER_USEC),
6297 div_u64(cfs_b->quota, NSEC_PER_USEC));
6298 }
6299
6300 /* reset count so we don't come right back in here */
6301 count = 0;
6302 }
6303 }
6304 if (idle)
6305 cfs_b->period_active = 0;
6306 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
6307
6308 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
6309 }
6310
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6311 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent)
6312 {
6313 raw_spin_lock_init(&cfs_b->lock);
6314 cfs_b->runtime = 0;
6315 cfs_b->quota = RUNTIME_INF;
6316 cfs_b->period = ns_to_ktime(default_cfs_period());
6317 cfs_b->burst = 0;
6318 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF;
6319
6320 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
6321 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
6322 cfs_b->period_timer.function = sched_cfs_period_timer;
6323
6324 /* Add a random offset so that timers interleave */
6325 hrtimer_set_expires(&cfs_b->period_timer,
6326 get_random_u32_below(cfs_b->period));
6327 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
6328 cfs_b->slack_timer.function = sched_cfs_slack_timer;
6329 cfs_b->slack_started = false;
6330 }
6331
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6332 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
6333 {
6334 cfs_rq->runtime_enabled = 0;
6335 INIT_LIST_HEAD(&cfs_rq->throttled_list);
6336 #ifdef CONFIG_SMP
6337 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list);
6338 #endif
6339 }
6340
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6341 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6342 {
6343 lockdep_assert_held(&cfs_b->lock);
6344
6345 if (cfs_b->period_active)
6346 return;
6347
6348 cfs_b->period_active = 1;
6349 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
6350 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
6351 }
6352
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6353 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
6354 {
6355 int __maybe_unused i;
6356
6357 /* init_cfs_bandwidth() was not called */
6358 if (!cfs_b->throttled_cfs_rq.next)
6359 return;
6360
6361 hrtimer_cancel(&cfs_b->period_timer);
6362 hrtimer_cancel(&cfs_b->slack_timer);
6363
6364 /*
6365 * It is possible that we still have some cfs_rq's pending on a CSD
6366 * list, though this race is very rare. In order for this to occur, we
6367 * must have raced with the last task leaving the group while there
6368 * exist throttled cfs_rq(s), and the period_timer must have queued the
6369 * CSD item but the remote cpu has not yet processed it. To handle this,
6370 * we can simply flush all pending CSD work inline here. We're
6371 * guaranteed at this point that no additional cfs_rq of this group can
6372 * join a CSD list.
6373 */
6374 #ifdef CONFIG_SMP
6375 for_each_possible_cpu(i) {
6376 struct rq *rq = cpu_rq(i);
6377 unsigned long flags;
6378
6379 if (list_empty(&rq->cfsb_csd_list))
6380 continue;
6381
6382 local_irq_save(flags);
6383 __cfsb_csd_unthrottle(rq);
6384 local_irq_restore(flags);
6385 }
6386 #endif
6387 }
6388
6389 /*
6390 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
6391 *
6392 * The race is harmless, since modifying bandwidth settings of unhooked group
6393 * bits doesn't do much.
6394 */
6395
6396 /* cpu online callback */
update_runtime_enabled(struct rq * rq)6397 static void __maybe_unused update_runtime_enabled(struct rq *rq)
6398 {
6399 struct task_group *tg;
6400
6401 lockdep_assert_rq_held(rq);
6402
6403 rcu_read_lock();
6404 list_for_each_entry_rcu(tg, &task_groups, list) {
6405 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6406 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6407
6408 raw_spin_lock(&cfs_b->lock);
6409 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
6410 raw_spin_unlock(&cfs_b->lock);
6411 }
6412 rcu_read_unlock();
6413 }
6414
6415 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)6416 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
6417 {
6418 struct task_group *tg;
6419
6420 lockdep_assert_rq_held(rq);
6421
6422 /*
6423 * The rq clock has already been updated in the
6424 * set_rq_offline(), so we should skip updating
6425 * the rq clock again in unthrottle_cfs_rq().
6426 */
6427 rq_clock_start_loop_update(rq);
6428
6429 rcu_read_lock();
6430 list_for_each_entry_rcu(tg, &task_groups, list) {
6431 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
6432
6433 if (!cfs_rq->runtime_enabled)
6434 continue;
6435
6436 /*
6437 * clock_task is not advancing so we just need to make sure
6438 * there's some valid quota amount
6439 */
6440 cfs_rq->runtime_remaining = 1;
6441 /*
6442 * Offline rq is schedulable till CPU is completely disabled
6443 * in take_cpu_down(), so we prevent new cfs throttling here.
6444 */
6445 cfs_rq->runtime_enabled = 0;
6446
6447 if (cfs_rq_throttled(cfs_rq))
6448 unthrottle_cfs_rq(cfs_rq);
6449 }
6450 rcu_read_unlock();
6451
6452 rq_clock_stop_loop_update(rq);
6453 }
6454
cfs_task_bw_constrained(struct task_struct * p)6455 bool cfs_task_bw_constrained(struct task_struct *p)
6456 {
6457 struct cfs_rq *cfs_rq = task_cfs_rq(p);
6458
6459 if (!cfs_bandwidth_used())
6460 return false;
6461
6462 if (cfs_rq->runtime_enabled ||
6463 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF)
6464 return true;
6465
6466 return false;
6467 }
6468
6469 #ifdef CONFIG_NO_HZ_FULL
6470 /* called from pick_next_task_fair() */
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6471 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p)
6472 {
6473 int cpu = cpu_of(rq);
6474
6475 if (!sched_feat(HZ_BW) || !cfs_bandwidth_used())
6476 return;
6477
6478 if (!tick_nohz_full_cpu(cpu))
6479 return;
6480
6481 if (rq->nr_running != 1)
6482 return;
6483
6484 /*
6485 * We know there is only one task runnable and we've just picked it. The
6486 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will
6487 * be otherwise able to stop the tick. Just need to check if we are using
6488 * bandwidth control.
6489 */
6490 if (cfs_task_bw_constrained(p))
6491 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED);
6492 }
6493 #endif
6494
6495 #else /* CONFIG_CFS_BANDWIDTH */
6496
cfs_bandwidth_used(void)6497 static inline bool cfs_bandwidth_used(void)
6498 {
6499 return false;
6500 }
6501
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)6502 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)6503 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)6504 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)6505 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)6506 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6507
cfs_rq_throttled(struct cfs_rq * cfs_rq)6508 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
6509 {
6510 return 0;
6511 }
6512
throttled_hierarchy(struct cfs_rq * cfs_rq)6513 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
6514 {
6515 return 0;
6516 }
6517
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)6518 static inline int throttled_lb_pair(struct task_group *tg,
6519 int src_cpu, int dest_cpu)
6520 {
6521 return 0;
6522 }
6523
6524 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b,struct cfs_bandwidth * parent)6525 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {}
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)6526 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
6527 #endif
6528
tg_cfs_bandwidth(struct task_group * tg)6529 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
6530 {
6531 return NULL;
6532 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)6533 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)6534 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)6535 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
6536 #ifdef CONFIG_CGROUP_SCHED
cfs_task_bw_constrained(struct task_struct * p)6537 bool cfs_task_bw_constrained(struct task_struct *p)
6538 {
6539 return false;
6540 }
6541 #endif
6542 #endif /* CONFIG_CFS_BANDWIDTH */
6543
6544 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL)
sched_fair_update_stop_tick(struct rq * rq,struct task_struct * p)6545 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {}
6546 #endif
6547
6548 /**************************************************
6549 * CFS operations on tasks:
6550 */
6551
6552 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)6553 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
6554 {
6555 struct sched_entity *se = &p->se;
6556
6557 SCHED_WARN_ON(task_rq(p) != rq);
6558
6559 if (rq->cfs.h_nr_running > 1) {
6560 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
6561 u64 slice = se->slice;
6562 s64 delta = slice - ran;
6563
6564 if (delta < 0) {
6565 if (task_current(rq, p))
6566 resched_curr(rq);
6567 return;
6568 }
6569 hrtick_start(rq, delta);
6570 }
6571 }
6572
6573 /*
6574 * called from enqueue/dequeue and updates the hrtick when the
6575 * current task is from our class and nr_running is low enough
6576 * to matter.
6577 */
hrtick_update(struct rq * rq)6578 static void hrtick_update(struct rq *rq)
6579 {
6580 struct task_struct *curr = rq->curr;
6581
6582 if (!hrtick_enabled_fair(rq) || curr->sched_class != &fair_sched_class)
6583 return;
6584
6585 hrtick_start_fair(rq, curr);
6586 }
6587 #else /* !CONFIG_SCHED_HRTICK */
6588 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)6589 hrtick_start_fair(struct rq *rq, struct task_struct *p)
6590 {
6591 }
6592
hrtick_update(struct rq * rq)6593 static inline void hrtick_update(struct rq *rq)
6594 {
6595 }
6596 #endif
6597
6598 #ifdef CONFIG_SMP
cpu_overutilized(int cpu)6599 static inline bool cpu_overutilized(int cpu)
6600 {
6601 unsigned long rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN);
6602 unsigned long rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX);
6603
6604 /* Return true only if the utilization doesn't fit CPU's capacity */
6605 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu);
6606 }
6607
update_overutilized_status(struct rq * rq)6608 static inline void update_overutilized_status(struct rq *rq)
6609 {
6610 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
6611 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
6612 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
6613 }
6614 }
6615 #else
update_overutilized_status(struct rq * rq)6616 static inline void update_overutilized_status(struct rq *rq) { }
6617 #endif
6618
6619 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)6620 static int sched_idle_rq(struct rq *rq)
6621 {
6622 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
6623 rq->nr_running);
6624 }
6625
6626 #ifdef CONFIG_SMP
sched_idle_cpu(int cpu)6627 static int sched_idle_cpu(int cpu)
6628 {
6629 return sched_idle_rq(cpu_rq(cpu));
6630 }
6631 #endif
6632
6633 static void set_next_buddy(struct sched_entity *se);
6634
6635 #ifdef CONFIG_SCHED_LATENCY_NICE
check_preempt_from_idle(struct cfs_rq * cfs,struct sched_entity * se)6636 static void check_preempt_from_idle(struct cfs_rq *cfs, struct sched_entity *se)
6637 {
6638 struct sched_entity *next;
6639
6640 if (se->latency_weight <= 0)
6641 return;
6642
6643 if (cfs->nr_running <= 1)
6644 return;
6645 /*
6646 * When waking from idle, we don't need to check to preempt at wakeup
6647 * the idle thread and don't set next buddy as a candidate for being
6648 * picked in priority.
6649 * In case of simultaneous wakeup from idle, the latency sensitive tasks
6650 * lost opportunity to preempt non sensitive tasks which woke up
6651 * simultaneously.
6652 */
6653
6654 if (cfs->next)
6655 next = cfs->next;
6656 else
6657 next = __pick_first_entity(cfs);
6658
6659 if (next && wakeup_preempt_entity(next, se) == 1)
6660 set_next_buddy(se);
6661 }
6662 #endif
6663
6664 /*
6665 * The enqueue_task method is called before nr_running is
6666 * increased. Here we update the fair scheduling stats and
6667 * then put the task into the rbtree:
6668 */
6669 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)6670 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6671 {
6672 struct cfs_rq *cfs_rq;
6673 struct sched_entity *se = &p->se;
6674 int idle_h_nr_running = task_has_idle_policy(p);
6675 int task_new = !(flags & ENQUEUE_WAKEUP);
6676
6677 /*
6678 * The code below (indirectly) updates schedutil which looks at
6679 * the cfs_rq utilization to select a frequency.
6680 * Let's add the task's estimated utilization to the cfs_rq's
6681 * estimated utilization, before we update schedutil.
6682 */
6683 util_est_enqueue(&rq->cfs, p);
6684
6685 /*
6686 * If in_iowait is set, the code below may not trigger any cpufreq
6687 * utilization updates, so do it here explicitly with the IOWAIT flag
6688 * passed.
6689 */
6690 if (p->in_iowait)
6691 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
6692
6693 for_each_sched_entity(se) {
6694 if (se->on_rq)
6695 break;
6696 cfs_rq = cfs_rq_of(se);
6697 enqueue_entity(cfs_rq, se, flags);
6698
6699 cfs_rq->h_nr_running++;
6700 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6701
6702 if (cfs_rq_is_idle(cfs_rq))
6703 idle_h_nr_running = 1;
6704
6705 /* end evaluation on encountering a throttled cfs_rq */
6706 if (cfs_rq_throttled(cfs_rq))
6707 goto enqueue_throttle;
6708
6709 flags = ENQUEUE_WAKEUP;
6710 }
6711
6712 for_each_sched_entity(se) {
6713 cfs_rq = cfs_rq_of(se);
6714
6715 update_load_avg(cfs_rq, se, UPDATE_TG);
6716 se_update_runnable(se);
6717 update_cfs_group(se);
6718
6719 cfs_rq->h_nr_running++;
6720 cfs_rq->idle_h_nr_running += idle_h_nr_running;
6721
6722 if (cfs_rq_is_idle(cfs_rq))
6723 idle_h_nr_running = 1;
6724
6725 /* end evaluation on encountering a throttled cfs_rq */
6726 if (cfs_rq_throttled(cfs_rq))
6727 goto enqueue_throttle;
6728 }
6729
6730 /* At this point se is NULL and we are at root level*/
6731 add_nr_running(rq, 1);
6732
6733 /*
6734 * Since new tasks are assigned an initial util_avg equal to
6735 * half of the spare capacity of their CPU, tiny tasks have the
6736 * ability to cross the overutilized threshold, which will
6737 * result in the load balancer ruining all the task placement
6738 * done by EAS. As a way to mitigate that effect, do not account
6739 * for the first enqueue operation of new tasks during the
6740 * overutilized flag detection.
6741 *
6742 * A better way of solving this problem would be to wait for
6743 * the PELT signals of tasks to converge before taking them
6744 * into account, but that is not straightforward to implement,
6745 * and the following generally works well enough in practice.
6746 */
6747 if (!task_new)
6748 update_overutilized_status(rq);
6749
6750 #ifdef CONFIG_SCHED_LATENCY_NICE
6751 if (rq->curr == rq->idle)
6752 check_preempt_from_idle(cfs_rq_of(&p->se), &p->se);
6753 #endif
6754
6755 enqueue_throttle:
6756 assert_list_leaf_cfs_rq(rq);
6757
6758 hrtick_update(rq);
6759 }
6760
6761 static void set_next_buddy(struct sched_entity *se);
6762
6763 /*
6764 * The dequeue_task method is called before nr_running is
6765 * decreased. We remove the task from the rbtree and
6766 * update the fair scheduling stats:
6767 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)6768 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
6769 {
6770 struct cfs_rq *cfs_rq;
6771 struct sched_entity *se = &p->se;
6772 int task_sleep = flags & DEQUEUE_SLEEP;
6773 int idle_h_nr_running = task_has_idle_policy(p);
6774 bool was_sched_idle = sched_idle_rq(rq);
6775
6776 util_est_dequeue(&rq->cfs, p);
6777
6778 for_each_sched_entity(se) {
6779 cfs_rq = cfs_rq_of(se);
6780 dequeue_entity(cfs_rq, se, flags);
6781
6782 cfs_rq->h_nr_running--;
6783 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6784
6785 if (cfs_rq_is_idle(cfs_rq))
6786 idle_h_nr_running = 1;
6787
6788 /* end evaluation on encountering a throttled cfs_rq */
6789 if (cfs_rq_throttled(cfs_rq))
6790 goto dequeue_throttle;
6791
6792 /* Don't dequeue parent if it has other entities besides us */
6793 if (cfs_rq->load.weight) {
6794 /* Avoid re-evaluating load for this entity: */
6795 se = parent_entity(se);
6796 /*
6797 * Bias pick_next to pick a task from this cfs_rq, as
6798 * p is sleeping when it is within its sched_slice.
6799 */
6800 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
6801 set_next_buddy(se);
6802 break;
6803 }
6804 flags |= DEQUEUE_SLEEP;
6805 }
6806
6807 for_each_sched_entity(se) {
6808 cfs_rq = cfs_rq_of(se);
6809
6810 update_load_avg(cfs_rq, se, UPDATE_TG);
6811 se_update_runnable(se);
6812 update_cfs_group(se);
6813
6814 cfs_rq->h_nr_running--;
6815 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
6816
6817 if (cfs_rq_is_idle(cfs_rq))
6818 idle_h_nr_running = 1;
6819
6820 /* end evaluation on encountering a throttled cfs_rq */
6821 if (cfs_rq_throttled(cfs_rq))
6822 goto dequeue_throttle;
6823
6824 }
6825
6826 /* At this point se is NULL and we are at root level*/
6827 sub_nr_running(rq, 1);
6828
6829 /* balance early to pull high priority tasks */
6830 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
6831 rq->next_balance = jiffies;
6832
6833 dequeue_throttle:
6834 util_est_update(&rq->cfs, p, task_sleep);
6835 hrtick_update(rq);
6836 }
6837
6838 #ifdef CONFIG_SMP
6839
6840 /* Working cpumask for: load_balance, load_balance_newidle. */
6841 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6842 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask);
6843 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask);
6844
6845 #ifdef CONFIG_NO_HZ_COMMON
6846
6847 static struct {
6848 cpumask_var_t idle_cpus_mask;
6849 atomic_t nr_cpus;
6850 int has_blocked; /* Idle CPUS has blocked load */
6851 int needs_update; /* Newly idle CPUs need their next_balance collated */
6852 unsigned long next_balance; /* in jiffy units */
6853 unsigned long next_blocked; /* Next update of blocked load in jiffies */
6854 } nohz ____cacheline_aligned;
6855
6856 #endif /* CONFIG_NO_HZ_COMMON */
6857
cpu_load(struct rq * rq)6858 static unsigned long cpu_load(struct rq *rq)
6859 {
6860 return cfs_rq_load_avg(&rq->cfs);
6861 }
6862
6863 /*
6864 * cpu_load_without - compute CPU load without any contributions from *p
6865 * @cpu: the CPU which load is requested
6866 * @p: the task which load should be discounted
6867 *
6868 * The load of a CPU is defined by the load of tasks currently enqueued on that
6869 * CPU as well as tasks which are currently sleeping after an execution on that
6870 * CPU.
6871 *
6872 * This method returns the load of the specified CPU by discounting the load of
6873 * the specified task, whenever the task is currently contributing to the CPU
6874 * load.
6875 */
cpu_load_without(struct rq * rq,struct task_struct * p)6876 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
6877 {
6878 struct cfs_rq *cfs_rq;
6879 unsigned int load;
6880
6881 /* Task has no contribution or is new */
6882 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6883 return cpu_load(rq);
6884
6885 cfs_rq = &rq->cfs;
6886 load = READ_ONCE(cfs_rq->avg.load_avg);
6887
6888 /* Discount task's util from CPU's util */
6889 lsub_positive(&load, task_h_load(p));
6890
6891 return load;
6892 }
6893
cpu_runnable(struct rq * rq)6894 static unsigned long cpu_runnable(struct rq *rq)
6895 {
6896 return cfs_rq_runnable_avg(&rq->cfs);
6897 }
6898
cpu_runnable_without(struct rq * rq,struct task_struct * p)6899 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
6900 {
6901 struct cfs_rq *cfs_rq;
6902 unsigned int runnable;
6903
6904 /* Task has no contribution or is new */
6905 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6906 return cpu_runnable(rq);
6907
6908 cfs_rq = &rq->cfs;
6909 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6910
6911 /* Discount task's runnable from CPU's runnable */
6912 lsub_positive(&runnable, p->se.avg.runnable_avg);
6913
6914 return runnable;
6915 }
6916
capacity_of(int cpu)6917 static unsigned long capacity_of(int cpu)
6918 {
6919 return cpu_rq(cpu)->cpu_capacity;
6920 }
6921
record_wakee(struct task_struct * p)6922 static void record_wakee(struct task_struct *p)
6923 {
6924 /*
6925 * Only decay a single time; tasks that have less then 1 wakeup per
6926 * jiffy will not have built up many flips.
6927 */
6928 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6929 current->wakee_flips >>= 1;
6930 current->wakee_flip_decay_ts = jiffies;
6931 }
6932
6933 if (current->last_wakee != p) {
6934 current->last_wakee = p;
6935 current->wakee_flips++;
6936 }
6937 }
6938
6939 /*
6940 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6941 *
6942 * A waker of many should wake a different task than the one last awakened
6943 * at a frequency roughly N times higher than one of its wakees.
6944 *
6945 * In order to determine whether we should let the load spread vs consolidating
6946 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6947 * partner, and a factor of lls_size higher frequency in the other.
6948 *
6949 * With both conditions met, we can be relatively sure that the relationship is
6950 * non-monogamous, with partner count exceeding socket size.
6951 *
6952 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6953 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6954 * socket size.
6955 */
wake_wide(struct task_struct * p)6956 static int wake_wide(struct task_struct *p)
6957 {
6958 unsigned int master = current->wakee_flips;
6959 unsigned int slave = p->wakee_flips;
6960 int factor = __this_cpu_read(sd_llc_size);
6961
6962 if (master < slave)
6963 swap(master, slave);
6964 if (slave < factor || master < slave * factor)
6965 return 0;
6966 return 1;
6967 }
6968
6969 /*
6970 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6971 * soonest. For the purpose of speed we only consider the waking and previous
6972 * CPU.
6973 *
6974 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6975 * cache-affine and is (or will be) idle.
6976 *
6977 * wake_affine_weight() - considers the weight to reflect the average
6978 * scheduling latency of the CPUs. This seems to work
6979 * for the overloaded case.
6980 */
6981 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)6982 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6983 {
6984 /*
6985 * If this_cpu is idle, it implies the wakeup is from interrupt
6986 * context. Only allow the move if cache is shared. Otherwise an
6987 * interrupt intensive workload could force all tasks onto one
6988 * node depending on the IO topology or IRQ affinity settings.
6989 *
6990 * If the prev_cpu is idle and cache affine then avoid a migration.
6991 * There is no guarantee that the cache hot data from an interrupt
6992 * is more important than cache hot data on the prev_cpu and from
6993 * a cpufreq perspective, it's better to have higher utilisation
6994 * on one CPU.
6995 */
6996 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6997 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6998
6999 if (sync && cpu_rq(this_cpu)->nr_running == 1)
7000 return this_cpu;
7001
7002 if (available_idle_cpu(prev_cpu))
7003 return prev_cpu;
7004
7005 return nr_cpumask_bits;
7006 }
7007
7008 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7009 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
7010 int this_cpu, int prev_cpu, int sync)
7011 {
7012 s64 this_eff_load, prev_eff_load;
7013 unsigned long task_load;
7014
7015 this_eff_load = cpu_load(cpu_rq(this_cpu));
7016
7017 if (sync) {
7018 unsigned long current_load = task_h_load(current);
7019
7020 if (current_load > this_eff_load)
7021 return this_cpu;
7022
7023 this_eff_load -= current_load;
7024 }
7025
7026 task_load = task_h_load(p);
7027
7028 this_eff_load += task_load;
7029 if (sched_feat(WA_BIAS))
7030 this_eff_load *= 100;
7031 this_eff_load *= capacity_of(prev_cpu);
7032
7033 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
7034 prev_eff_load -= task_load;
7035 if (sched_feat(WA_BIAS))
7036 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
7037 prev_eff_load *= capacity_of(this_cpu);
7038
7039 /*
7040 * If sync, adjust the weight of prev_eff_load such that if
7041 * prev_eff == this_eff that select_idle_sibling() will consider
7042 * stacking the wakee on top of the waker if no other CPU is
7043 * idle.
7044 */
7045 if (sync)
7046 prev_eff_load += 1;
7047
7048 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
7049 }
7050
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)7051 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
7052 int this_cpu, int prev_cpu, int sync)
7053 {
7054 int target = nr_cpumask_bits;
7055
7056 if (sched_feat(WA_IDLE))
7057 target = wake_affine_idle(this_cpu, prev_cpu, sync);
7058
7059 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
7060 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
7061
7062 schedstat_inc(p->stats.nr_wakeups_affine_attempts);
7063 if (target != this_cpu)
7064 return prev_cpu;
7065
7066 schedstat_inc(sd->ttwu_move_affine);
7067 schedstat_inc(p->stats.nr_wakeups_affine);
7068 return target;
7069 }
7070
7071 static struct sched_group *
7072 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
7073
7074 /*
7075 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
7076 */
7077 static int
find_idlest_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)7078 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
7079 {
7080 unsigned long load, min_load = ULONG_MAX;
7081 unsigned int min_exit_latency = UINT_MAX;
7082 u64 latest_idle_timestamp = 0;
7083 int least_loaded_cpu = this_cpu;
7084 int shallowest_idle_cpu = -1;
7085 int i;
7086
7087 /* Check if we have any choice: */
7088 if (group->group_weight == 1)
7089 return cpumask_first(sched_group_span(group));
7090
7091 /* Traverse only the allowed CPUs */
7092 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
7093 struct rq *rq = cpu_rq(i);
7094
7095 if (!sched_core_cookie_match(rq, p))
7096 continue;
7097
7098 if (sched_idle_cpu(i))
7099 return i;
7100
7101 if (available_idle_cpu(i)) {
7102 struct cpuidle_state *idle = idle_get_state(rq);
7103 if (idle && idle->exit_latency < min_exit_latency) {
7104 /*
7105 * We give priority to a CPU whose idle state
7106 * has the smallest exit latency irrespective
7107 * of any idle timestamp.
7108 */
7109 min_exit_latency = idle->exit_latency;
7110 latest_idle_timestamp = rq->idle_stamp;
7111 shallowest_idle_cpu = i;
7112 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
7113 rq->idle_stamp > latest_idle_timestamp) {
7114 /*
7115 * If equal or no active idle state, then
7116 * the most recently idled CPU might have
7117 * a warmer cache.
7118 */
7119 latest_idle_timestamp = rq->idle_stamp;
7120 shallowest_idle_cpu = i;
7121 }
7122 } else if (shallowest_idle_cpu == -1) {
7123 load = cpu_load(cpu_rq(i));
7124 if (load < min_load) {
7125 min_load = load;
7126 least_loaded_cpu = i;
7127 }
7128 }
7129 }
7130
7131 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
7132 }
7133
find_idlest_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)7134 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
7135 int cpu, int prev_cpu, int sd_flag)
7136 {
7137 int new_cpu = cpu;
7138
7139 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
7140 return prev_cpu;
7141
7142 /*
7143 * We need task's util for cpu_util_without, sync it up to
7144 * prev_cpu's last_update_time.
7145 */
7146 if (!(sd_flag & SD_BALANCE_FORK))
7147 sync_entity_load_avg(&p->se);
7148
7149 while (sd) {
7150 struct sched_group *group;
7151 struct sched_domain *tmp;
7152 int weight;
7153
7154 if (!(sd->flags & sd_flag)) {
7155 sd = sd->child;
7156 continue;
7157 }
7158
7159 group = find_idlest_group(sd, p, cpu);
7160 if (!group) {
7161 sd = sd->child;
7162 continue;
7163 }
7164
7165 new_cpu = find_idlest_group_cpu(group, p, cpu);
7166 if (new_cpu == cpu) {
7167 /* Now try balancing at a lower domain level of 'cpu': */
7168 sd = sd->child;
7169 continue;
7170 }
7171
7172 /* Now try balancing at a lower domain level of 'new_cpu': */
7173 cpu = new_cpu;
7174 weight = sd->span_weight;
7175 sd = NULL;
7176 for_each_domain(cpu, tmp) {
7177 if (weight <= tmp->span_weight)
7178 break;
7179 if (tmp->flags & sd_flag)
7180 sd = tmp;
7181 }
7182 }
7183
7184 return new_cpu;
7185 }
7186
__select_idle_cpu(int cpu,struct task_struct * p)7187 static inline int __select_idle_cpu(int cpu, struct task_struct *p)
7188 {
7189 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) &&
7190 sched_cpu_cookie_match(cpu_rq(cpu), p))
7191 return cpu;
7192
7193 return -1;
7194 }
7195
7196 #ifdef CONFIG_SCHED_SMT
7197 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
7198 EXPORT_SYMBOL_GPL(sched_smt_present);
7199
set_idle_cores(int cpu,int val)7200 static inline void set_idle_cores(int cpu, int val)
7201 {
7202 struct sched_domain_shared *sds;
7203
7204 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7205 if (sds)
7206 WRITE_ONCE(sds->has_idle_cores, val);
7207 }
7208
test_idle_cores(int cpu)7209 static inline bool test_idle_cores(int cpu)
7210 {
7211 struct sched_domain_shared *sds;
7212
7213 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
7214 if (sds)
7215 return READ_ONCE(sds->has_idle_cores);
7216
7217 return false;
7218 }
7219
7220 /*
7221 * Scans the local SMT mask to see if the entire core is idle, and records this
7222 * information in sd_llc_shared->has_idle_cores.
7223 *
7224 * Since SMT siblings share all cache levels, inspecting this limited remote
7225 * state should be fairly cheap.
7226 */
__update_idle_core(struct rq * rq)7227 void __update_idle_core(struct rq *rq)
7228 {
7229 int core = cpu_of(rq);
7230 int cpu;
7231
7232 rcu_read_lock();
7233 if (test_idle_cores(core))
7234 goto unlock;
7235
7236 for_each_cpu(cpu, cpu_smt_mask(core)) {
7237 if (cpu == core)
7238 continue;
7239
7240 if (!available_idle_cpu(cpu))
7241 goto unlock;
7242 }
7243
7244 set_idle_cores(core, 1);
7245 unlock:
7246 rcu_read_unlock();
7247 }
7248
7249 /*
7250 * Scan the entire LLC domain for idle cores; this dynamically switches off if
7251 * there are no idle cores left in the system; tracked through
7252 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
7253 */
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7254 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7255 {
7256 bool idle = true;
7257 int cpu;
7258
7259 for_each_cpu(cpu, cpu_smt_mask(core)) {
7260 if (!available_idle_cpu(cpu)) {
7261 idle = false;
7262 if (*idle_cpu == -1) {
7263 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) {
7264 *idle_cpu = cpu;
7265 break;
7266 }
7267 continue;
7268 }
7269 break;
7270 }
7271 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus))
7272 *idle_cpu = cpu;
7273 }
7274
7275 if (idle)
7276 return core;
7277
7278 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
7279 return -1;
7280 }
7281
7282 /*
7283 * Scan the local SMT mask for idle CPUs.
7284 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7285 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7286 {
7287 int cpu;
7288
7289 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) {
7290 if (cpu == target)
7291 continue;
7292 /*
7293 * Check if the CPU is in the LLC scheduling domain of @target.
7294 * Due to isolcpus, there is no guarantee that all the siblings are in the domain.
7295 */
7296 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7297 continue;
7298 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
7299 return cpu;
7300 }
7301
7302 return -1;
7303 }
7304
7305 #else /* CONFIG_SCHED_SMT */
7306
set_idle_cores(int cpu,int val)7307 static inline void set_idle_cores(int cpu, int val)
7308 {
7309 }
7310
test_idle_cores(int cpu)7311 static inline bool test_idle_cores(int cpu)
7312 {
7313 return false;
7314 }
7315
select_idle_core(struct task_struct * p,int core,struct cpumask * cpus,int * idle_cpu)7316 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu)
7317 {
7318 return __select_idle_cpu(core, p);
7319 }
7320
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)7321 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
7322 {
7323 return -1;
7324 }
7325
7326 #endif /* CONFIG_SCHED_SMT */
7327
7328 /*
7329 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
7330 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
7331 * average idle time for this rq (as found in rq->avg_idle).
7332 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,bool has_idle_core,int target)7333 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target)
7334 {
7335 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7336 int i, cpu, idle_cpu = -1, nr = INT_MAX;
7337 struct sched_domain_shared *sd_share;
7338 struct rq *this_rq = this_rq();
7339 int this = smp_processor_id();
7340 struct sched_domain *this_sd = NULL;
7341 u64 time = 0;
7342
7343 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7344
7345 if (sched_feat(SIS_PROP) && !has_idle_core) {
7346 u64 avg_cost, avg_idle, span_avg;
7347 unsigned long now = jiffies;
7348
7349 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
7350 if (!this_sd)
7351 return -1;
7352
7353 /*
7354 * If we're busy, the assumption that the last idle period
7355 * predicts the future is flawed; age away the remaining
7356 * predicted idle time.
7357 */
7358 if (unlikely(this_rq->wake_stamp < now)) {
7359 while (this_rq->wake_stamp < now && this_rq->wake_avg_idle) {
7360 this_rq->wake_stamp++;
7361 this_rq->wake_avg_idle >>= 1;
7362 }
7363 }
7364
7365 avg_idle = this_rq->wake_avg_idle;
7366 avg_cost = this_sd->avg_scan_cost + 1;
7367
7368 span_avg = sd->span_weight * avg_idle;
7369 if (span_avg > 4*avg_cost)
7370 nr = div_u64(span_avg, avg_cost);
7371 else
7372 nr = 4;
7373
7374 time = cpu_clock(this);
7375 }
7376
7377 if (sched_feat(SIS_UTIL)) {
7378 sd_share = rcu_dereference(per_cpu(sd_llc_shared, target));
7379 if (sd_share) {
7380 /* because !--nr is the condition to stop scan */
7381 nr = READ_ONCE(sd_share->nr_idle_scan) + 1;
7382 /* overloaded LLC is unlikely to have idle cpu/core */
7383 if (nr == 1)
7384 return -1;
7385 }
7386 }
7387
7388 for_each_cpu_wrap(cpu, cpus, target + 1) {
7389 if (has_idle_core) {
7390 i = select_idle_core(p, cpu, cpus, &idle_cpu);
7391 if ((unsigned int)i < nr_cpumask_bits)
7392 return i;
7393
7394 } else {
7395 if (!--nr)
7396 return -1;
7397 idle_cpu = __select_idle_cpu(cpu, p);
7398 if ((unsigned int)idle_cpu < nr_cpumask_bits)
7399 break;
7400 }
7401 }
7402
7403 if (has_idle_core)
7404 set_idle_cores(target, false);
7405
7406 if (sched_feat(SIS_PROP) && this_sd && !has_idle_core) {
7407 time = cpu_clock(this) - time;
7408
7409 /*
7410 * Account for the scan cost of wakeups against the average
7411 * idle time.
7412 */
7413 this_rq->wake_avg_idle -= min(this_rq->wake_avg_idle, time);
7414
7415 update_avg(&this_sd->avg_scan_cost, time);
7416 }
7417
7418 return idle_cpu;
7419 }
7420
7421 /*
7422 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
7423 * the task fits. If no CPU is big enough, but there are idle ones, try to
7424 * maximize capacity.
7425 */
7426 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)7427 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
7428 {
7429 unsigned long task_util, util_min, util_max, best_cap = 0;
7430 int fits, best_fits = 0;
7431 int cpu, best_cpu = -1;
7432 struct cpumask *cpus;
7433
7434 cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7435 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
7436
7437 task_util = task_util_est(p);
7438 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7439 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7440
7441 for_each_cpu_wrap(cpu, cpus, target) {
7442 unsigned long cpu_cap = capacity_of(cpu);
7443
7444 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
7445 continue;
7446
7447 fits = util_fits_cpu(task_util, util_min, util_max, cpu);
7448
7449 /* This CPU fits with all requirements */
7450 if (fits > 0)
7451 return cpu;
7452 /*
7453 * Only the min performance hint (i.e. uclamp_min) doesn't fit.
7454 * Look for the CPU with best capacity.
7455 */
7456 else if (fits < 0)
7457 cpu_cap = capacity_orig_of(cpu) - thermal_load_avg(cpu_rq(cpu));
7458
7459 /*
7460 * First, select CPU which fits better (-1 being better than 0).
7461 * Then, select the one with best capacity at same level.
7462 */
7463 if ((fits < best_fits) ||
7464 ((fits == best_fits) && (cpu_cap > best_cap))) {
7465 best_cap = cpu_cap;
7466 best_cpu = cpu;
7467 best_fits = fits;
7468 }
7469 }
7470
7471 return best_cpu;
7472 }
7473
asym_fits_cpu(unsigned long util,unsigned long util_min,unsigned long util_max,int cpu)7474 static inline bool asym_fits_cpu(unsigned long util,
7475 unsigned long util_min,
7476 unsigned long util_max,
7477 int cpu)
7478 {
7479 if (sched_asym_cpucap_active())
7480 /*
7481 * Return true only if the cpu fully fits the task requirements
7482 * which include the utilization and the performance hints.
7483 */
7484 return (util_fits_cpu(util, util_min, util_max, cpu) > 0);
7485
7486 return true;
7487 }
7488
7489 /*
7490 * Try and locate an idle core/thread in the LLC cache domain.
7491 */
select_idle_sibling(struct task_struct * p,int prev,int target)7492 static int select_idle_sibling(struct task_struct *p, int prev, int target)
7493 {
7494 bool has_idle_core = false;
7495 struct sched_domain *sd;
7496 unsigned long task_util, util_min, util_max;
7497 int i, recent_used_cpu;
7498
7499 /*
7500 * On asymmetric system, update task utilization because we will check
7501 * that the task fits with cpu's capacity.
7502 */
7503 if (sched_asym_cpucap_active()) {
7504 sync_entity_load_avg(&p->se);
7505 task_util = task_util_est(p);
7506 util_min = uclamp_eff_value(p, UCLAMP_MIN);
7507 util_max = uclamp_eff_value(p, UCLAMP_MAX);
7508 }
7509
7510 /*
7511 * per-cpu select_rq_mask usage
7512 */
7513 lockdep_assert_irqs_disabled();
7514
7515 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
7516 asym_fits_cpu(task_util, util_min, util_max, target))
7517 return target;
7518
7519 /*
7520 * If the previous CPU is cache affine and idle, don't be stupid:
7521 */
7522 if (prev != target && cpus_share_cache(prev, target) &&
7523 (available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
7524 asym_fits_cpu(task_util, util_min, util_max, prev))
7525 return prev;
7526
7527 /*
7528 * Allow a per-cpu kthread to stack with the wakee if the
7529 * kworker thread and the tasks previous CPUs are the same.
7530 * The assumption is that the wakee queued work for the
7531 * per-cpu kthread that is now complete and the wakeup is
7532 * essentially a sync wakeup. An obvious example of this
7533 * pattern is IO completions.
7534 */
7535 if (is_per_cpu_kthread(current) &&
7536 in_task() &&
7537 prev == smp_processor_id() &&
7538 this_rq()->nr_running <= 1 &&
7539 asym_fits_cpu(task_util, util_min, util_max, prev)) {
7540 return prev;
7541 }
7542
7543 /* Check a recently used CPU as a potential idle candidate: */
7544 recent_used_cpu = p->recent_used_cpu;
7545 p->recent_used_cpu = prev;
7546 if (recent_used_cpu != prev &&
7547 recent_used_cpu != target &&
7548 cpus_share_cache(recent_used_cpu, target) &&
7549 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
7550 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) &&
7551 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) {
7552 return recent_used_cpu;
7553 }
7554
7555 /*
7556 * For asymmetric CPU capacity systems, our domain of interest is
7557 * sd_asym_cpucapacity rather than sd_llc.
7558 */
7559 if (sched_asym_cpucap_active()) {
7560 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
7561 /*
7562 * On an asymmetric CPU capacity system where an exclusive
7563 * cpuset defines a symmetric island (i.e. one unique
7564 * capacity_orig value through the cpuset), the key will be set
7565 * but the CPUs within that cpuset will not have a domain with
7566 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
7567 * capacity path.
7568 */
7569 if (sd) {
7570 i = select_idle_capacity(p, sd, target);
7571 return ((unsigned)i < nr_cpumask_bits) ? i : target;
7572 }
7573 }
7574
7575 sd = rcu_dereference(per_cpu(sd_llc, target));
7576 if (!sd)
7577 return target;
7578
7579 if (sched_smt_active()) {
7580 has_idle_core = test_idle_cores(target);
7581
7582 if (!has_idle_core && cpus_share_cache(prev, target)) {
7583 i = select_idle_smt(p, sd, prev);
7584 if ((unsigned int)i < nr_cpumask_bits)
7585 return i;
7586 }
7587 }
7588
7589 i = select_idle_cpu(p, sd, has_idle_core, target);
7590 if ((unsigned)i < nr_cpumask_bits)
7591 return i;
7592
7593 return target;
7594 }
7595
7596 /**
7597 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks.
7598 * @cpu: the CPU to get the utilization for
7599 * @p: task for which the CPU utilization should be predicted or NULL
7600 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL
7601 * @boost: 1 to enable boosting, otherwise 0
7602 *
7603 * The unit of the return value must be the same as the one of CPU capacity
7604 * so that CPU utilization can be compared with CPU capacity.
7605 *
7606 * CPU utilization is the sum of running time of runnable tasks plus the
7607 * recent utilization of currently non-runnable tasks on that CPU.
7608 * It represents the amount of CPU capacity currently used by CFS tasks in
7609 * the range [0..max CPU capacity] with max CPU capacity being the CPU
7610 * capacity at f_max.
7611 *
7612 * The estimated CPU utilization is defined as the maximum between CPU
7613 * utilization and sum of the estimated utilization of the currently
7614 * runnable tasks on that CPU. It preserves a utilization "snapshot" of
7615 * previously-executed tasks, which helps better deduce how busy a CPU will
7616 * be when a long-sleeping task wakes up. The contribution to CPU utilization
7617 * of such a task would be significantly decayed at this point of time.
7618 *
7619 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization).
7620 * CPU contention for CFS tasks can be detected by CPU runnable > CPU
7621 * utilization. Boosting is implemented in cpu_util() so that internal
7622 * users (e.g. EAS) can use it next to external users (e.g. schedutil),
7623 * latter via cpu_util_cfs_boost().
7624 *
7625 * CPU utilization can be higher than the current CPU capacity
7626 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because
7627 * of rounding errors as well as task migrations or wakeups of new tasks.
7628 * CPU utilization has to be capped to fit into the [0..max CPU capacity]
7629 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%)
7630 * could be seen as over-utilized even though CPU1 has 20% of spare CPU
7631 * capacity. CPU utilization is allowed to overshoot current CPU capacity
7632 * though since this is useful for predicting the CPU capacity required
7633 * after task migrations (scheduler-driven DVFS).
7634 *
7635 * Return: (Boosted) (estimated) utilization for the specified CPU.
7636 */
7637 static unsigned long
cpu_util(int cpu,struct task_struct * p,int dst_cpu,int boost)7638 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost)
7639 {
7640 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
7641 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg);
7642 unsigned long runnable;
7643
7644 if (boost) {
7645 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
7646 util = max(util, runnable);
7647 }
7648
7649 /*
7650 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its
7651 * contribution. If @p migrates from another CPU to @cpu add its
7652 * contribution. In all the other cases @cpu is not impacted by the
7653 * migration so its util_avg is already correct.
7654 */
7655 if (p && task_cpu(p) == cpu && dst_cpu != cpu)
7656 lsub_positive(&util, task_util(p));
7657 else if (p && task_cpu(p) != cpu && dst_cpu == cpu)
7658 util += task_util(p);
7659
7660 if (sched_feat(UTIL_EST)) {
7661 unsigned long util_est;
7662
7663 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
7664
7665 /*
7666 * During wake-up @p isn't enqueued yet and doesn't contribute
7667 * to any cpu_rq(cpu)->cfs.avg.util_est.enqueued.
7668 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p
7669 * has been enqueued.
7670 *
7671 * During exec (@dst_cpu = -1) @p is enqueued and does
7672 * contribute to cpu_rq(cpu)->cfs.util_est.enqueued.
7673 * Remove it to "simulate" cpu_util without @p's contribution.
7674 *
7675 * Despite the task_on_rq_queued(@p) check there is still a
7676 * small window for a possible race when an exec
7677 * select_task_rq_fair() races with LB's detach_task().
7678 *
7679 * detach_task()
7680 * deactivate_task()
7681 * p->on_rq = TASK_ON_RQ_MIGRATING;
7682 * -------------------------------- A
7683 * dequeue_task() \
7684 * dequeue_task_fair() + Race Time
7685 * util_est_dequeue() /
7686 * -------------------------------- B
7687 *
7688 * The additional check "current == p" is required to further
7689 * reduce the race window.
7690 */
7691 if (dst_cpu == cpu)
7692 util_est += _task_util_est(p);
7693 else if (p && unlikely(task_on_rq_queued(p) || current == p))
7694 lsub_positive(&util_est, _task_util_est(p));
7695
7696 util = max(util, util_est);
7697 }
7698
7699 return min(util, capacity_orig_of(cpu));
7700 }
7701
cpu_util_cfs(int cpu)7702 unsigned long cpu_util_cfs(int cpu)
7703 {
7704 return cpu_util(cpu, NULL, -1, 0);
7705 }
7706
cpu_util_cfs_boost(int cpu)7707 unsigned long cpu_util_cfs_boost(int cpu)
7708 {
7709 return cpu_util(cpu, NULL, -1, 1);
7710 }
7711
7712 /*
7713 * cpu_util_without: compute cpu utilization without any contributions from *p
7714 * @cpu: the CPU which utilization is requested
7715 * @p: the task which utilization should be discounted
7716 *
7717 * The utilization of a CPU is defined by the utilization of tasks currently
7718 * enqueued on that CPU as well as tasks which are currently sleeping after an
7719 * execution on that CPU.
7720 *
7721 * This method returns the utilization of the specified CPU by discounting the
7722 * utilization of the specified task, whenever the task is currently
7723 * contributing to the CPU utilization.
7724 */
cpu_util_without(int cpu,struct task_struct * p)7725 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
7726 {
7727 /* Task has no contribution or is new */
7728 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
7729 p = NULL;
7730
7731 return cpu_util(cpu, p, -1, 0);
7732 }
7733
7734 /*
7735 * energy_env - Utilization landscape for energy estimation.
7736 * @task_busy_time: Utilization contribution by the task for which we test the
7737 * placement. Given by eenv_task_busy_time().
7738 * @pd_busy_time: Utilization of the whole perf domain without the task
7739 * contribution. Given by eenv_pd_busy_time().
7740 * @cpu_cap: Maximum CPU capacity for the perf domain.
7741 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap).
7742 */
7743 struct energy_env {
7744 unsigned long task_busy_time;
7745 unsigned long pd_busy_time;
7746 unsigned long cpu_cap;
7747 unsigned long pd_cap;
7748 };
7749
7750 /*
7751 * Compute the task busy time for compute_energy(). This time cannot be
7752 * injected directly into effective_cpu_util() because of the IRQ scaling.
7753 * The latter only makes sense with the most recent CPUs where the task has
7754 * run.
7755 */
eenv_task_busy_time(struct energy_env * eenv,struct task_struct * p,int prev_cpu)7756 static inline void eenv_task_busy_time(struct energy_env *eenv,
7757 struct task_struct *p, int prev_cpu)
7758 {
7759 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu);
7760 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu));
7761
7762 if (unlikely(irq >= max_cap))
7763 busy_time = max_cap;
7764 else
7765 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap);
7766
7767 eenv->task_busy_time = busy_time;
7768 }
7769
7770 /*
7771 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the
7772 * utilization for each @pd_cpus, it however doesn't take into account
7773 * clamping since the ratio (utilization / cpu_capacity) is already enough to
7774 * scale the EM reported power consumption at the (eventually clamped)
7775 * cpu_capacity.
7776 *
7777 * The contribution of the task @p for which we want to estimate the
7778 * energy cost is removed (by cpu_util()) and must be calculated
7779 * separately (see eenv_task_busy_time). This ensures:
7780 *
7781 * - A stable PD utilization, no matter which CPU of that PD we want to place
7782 * the task on.
7783 *
7784 * - A fair comparison between CPUs as the task contribution (task_util())
7785 * will always be the same no matter which CPU utilization we rely on
7786 * (util_avg or util_est).
7787 *
7788 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't
7789 * exceed @eenv->pd_cap.
7790 */
eenv_pd_busy_time(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p)7791 static inline void eenv_pd_busy_time(struct energy_env *eenv,
7792 struct cpumask *pd_cpus,
7793 struct task_struct *p)
7794 {
7795 unsigned long busy_time = 0;
7796 int cpu;
7797
7798 for_each_cpu(cpu, pd_cpus) {
7799 unsigned long util = cpu_util(cpu, p, -1, 0);
7800
7801 busy_time += effective_cpu_util(cpu, util, ENERGY_UTIL, NULL);
7802 }
7803
7804 eenv->pd_busy_time = min(eenv->pd_cap, busy_time);
7805 }
7806
7807 /*
7808 * Compute the maximum utilization for compute_energy() when the task @p
7809 * is placed on the cpu @dst_cpu.
7810 *
7811 * Returns the maximum utilization among @eenv->cpus. This utilization can't
7812 * exceed @eenv->cpu_cap.
7813 */
7814 static inline unsigned long
eenv_pd_max_util(struct energy_env * eenv,struct cpumask * pd_cpus,struct task_struct * p,int dst_cpu)7815 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus,
7816 struct task_struct *p, int dst_cpu)
7817 {
7818 unsigned long max_util = 0;
7819 int cpu;
7820
7821 for_each_cpu(cpu, pd_cpus) {
7822 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL;
7823 unsigned long util = cpu_util(cpu, p, dst_cpu, 1);
7824 unsigned long eff_util;
7825
7826 /*
7827 * Performance domain frequency: utilization clamping
7828 * must be considered since it affects the selection
7829 * of the performance domain frequency.
7830 * NOTE: in case RT tasks are running, by default the
7831 * FREQUENCY_UTIL's utilization can be max OPP.
7832 */
7833 eff_util = effective_cpu_util(cpu, util, FREQUENCY_UTIL, tsk);
7834 max_util = max(max_util, eff_util);
7835 }
7836
7837 return min(max_util, eenv->cpu_cap);
7838 }
7839
7840 /*
7841 * compute_energy(): Use the Energy Model to estimate the energy that @pd would
7842 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task
7843 * contribution is ignored.
7844 */
7845 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)7846 compute_energy(struct energy_env *eenv, struct perf_domain *pd,
7847 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu)
7848 {
7849 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu);
7850 unsigned long busy_time = eenv->pd_busy_time;
7851
7852 if (dst_cpu >= 0)
7853 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time);
7854
7855 return em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap);
7856 }
7857
7858 /*
7859 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
7860 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
7861 * spare capacity in each performance domain and uses it as a potential
7862 * candidate to execute the task. Then, it uses the Energy Model to figure
7863 * out which of the CPU candidates is the most energy-efficient.
7864 *
7865 * The rationale for this heuristic is as follows. In a performance domain,
7866 * all the most energy efficient CPU candidates (according to the Energy
7867 * Model) are those for which we'll request a low frequency. When there are
7868 * several CPUs for which the frequency request will be the same, we don't
7869 * have enough data to break the tie between them, because the Energy Model
7870 * only includes active power costs. With this model, if we assume that
7871 * frequency requests follow utilization (e.g. using schedutil), the CPU with
7872 * the maximum spare capacity in a performance domain is guaranteed to be among
7873 * the best candidates of the performance domain.
7874 *
7875 * In practice, it could be preferable from an energy standpoint to pack
7876 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
7877 * but that could also hurt our chances to go cluster idle, and we have no
7878 * ways to tell with the current Energy Model if this is actually a good
7879 * idea or not. So, find_energy_efficient_cpu() basically favors
7880 * cluster-packing, and spreading inside a cluster. That should at least be
7881 * a good thing for latency, and this is consistent with the idea that most
7882 * of the energy savings of EAS come from the asymmetry of the system, and
7883 * not so much from breaking the tie between identical CPUs. That's also the
7884 * reason why EAS is enabled in the topology code only for systems where
7885 * SD_ASYM_CPUCAPACITY is set.
7886 *
7887 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
7888 * they don't have any useful utilization data yet and it's not possible to
7889 * forecast their impact on energy consumption. Consequently, they will be
7890 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
7891 * to be energy-inefficient in some use-cases. The alternative would be to
7892 * bias new tasks towards specific types of CPUs first, or to try to infer
7893 * their util_avg from the parent task, but those heuristics could hurt
7894 * other use-cases too. So, until someone finds a better way to solve this,
7895 * let's keep things simple by re-using the existing slow path.
7896 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)7897 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
7898 {
7899 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
7900 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
7901 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0;
7902 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024;
7903 struct root_domain *rd = this_rq()->rd;
7904 int cpu, best_energy_cpu, target = -1;
7905 int prev_fits = -1, best_fits = -1;
7906 unsigned long best_thermal_cap = 0;
7907 unsigned long prev_thermal_cap = 0;
7908 struct sched_domain *sd;
7909 struct perf_domain *pd;
7910 struct energy_env eenv;
7911
7912 rcu_read_lock();
7913 pd = rcu_dereference(rd->pd);
7914 if (!pd || READ_ONCE(rd->overutilized))
7915 goto unlock;
7916
7917 /*
7918 * Energy-aware wake-up happens on the lowest sched_domain starting
7919 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
7920 */
7921 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
7922 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
7923 sd = sd->parent;
7924 if (!sd)
7925 goto unlock;
7926
7927 target = prev_cpu;
7928
7929 sync_entity_load_avg(&p->se);
7930 if (!task_util_est(p) && p_util_min == 0)
7931 goto unlock;
7932
7933 eenv_task_busy_time(&eenv, p, prev_cpu);
7934
7935 for (; pd; pd = pd->next) {
7936 unsigned long util_min = p_util_min, util_max = p_util_max;
7937 unsigned long cpu_cap, cpu_thermal_cap, util;
7938 long prev_spare_cap = -1, max_spare_cap = -1;
7939 unsigned long rq_util_min, rq_util_max;
7940 unsigned long cur_delta, base_energy;
7941 int max_spare_cap_cpu = -1;
7942 int fits, max_fits = -1;
7943
7944 cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask);
7945
7946 if (cpumask_empty(cpus))
7947 continue;
7948
7949 /* Account thermal pressure for the energy estimation */
7950 cpu = cpumask_first(cpus);
7951 cpu_thermal_cap = arch_scale_cpu_capacity(cpu);
7952 cpu_thermal_cap -= arch_scale_thermal_pressure(cpu);
7953
7954 eenv.cpu_cap = cpu_thermal_cap;
7955 eenv.pd_cap = 0;
7956
7957 for_each_cpu(cpu, cpus) {
7958 struct rq *rq = cpu_rq(cpu);
7959
7960 eenv.pd_cap += cpu_thermal_cap;
7961
7962 if (!cpumask_test_cpu(cpu, sched_domain_span(sd)))
7963 continue;
7964
7965 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
7966 continue;
7967
7968 util = cpu_util(cpu, p, cpu, 0);
7969 cpu_cap = capacity_of(cpu);
7970
7971 /*
7972 * Skip CPUs that cannot satisfy the capacity request.
7973 * IOW, placing the task there would make the CPU
7974 * overutilized. Take uclamp into account to see how
7975 * much capacity we can get out of the CPU; this is
7976 * aligned with sched_cpu_util().
7977 */
7978 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) {
7979 /*
7980 * Open code uclamp_rq_util_with() except for
7981 * the clamp() part. Ie: apply max aggregation
7982 * only. util_fits_cpu() logic requires to
7983 * operate on non clamped util but must use the
7984 * max-aggregated uclamp_{min, max}.
7985 */
7986 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN);
7987 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX);
7988
7989 util_min = max(rq_util_min, p_util_min);
7990 util_max = max(rq_util_max, p_util_max);
7991 }
7992
7993 fits = util_fits_cpu(util, util_min, util_max, cpu);
7994 if (!fits)
7995 continue;
7996
7997 lsub_positive(&cpu_cap, util);
7998
7999 if (cpu == prev_cpu) {
8000 /* Always use prev_cpu as a candidate. */
8001 prev_spare_cap = cpu_cap;
8002 prev_fits = fits;
8003 } else if ((fits > max_fits) ||
8004 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) {
8005 /*
8006 * Find the CPU with the maximum spare capacity
8007 * among the remaining CPUs in the performance
8008 * domain.
8009 */
8010 max_spare_cap = cpu_cap;
8011 max_spare_cap_cpu = cpu;
8012 max_fits = fits;
8013 }
8014 }
8015
8016 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0)
8017 continue;
8018
8019 eenv_pd_busy_time(&eenv, cpus, p);
8020 /* Compute the 'base' energy of the pd, without @p */
8021 base_energy = compute_energy(&eenv, pd, cpus, p, -1);
8022
8023 /* Evaluate the energy impact of using prev_cpu. */
8024 if (prev_spare_cap > -1) {
8025 prev_delta = compute_energy(&eenv, pd, cpus, p,
8026 prev_cpu);
8027 /* CPU utilization has changed */
8028 if (prev_delta < base_energy)
8029 goto unlock;
8030 prev_delta -= base_energy;
8031 prev_thermal_cap = cpu_thermal_cap;
8032 best_delta = min(best_delta, prev_delta);
8033 }
8034
8035 /* Evaluate the energy impact of using max_spare_cap_cpu. */
8036 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) {
8037 /* Current best energy cpu fits better */
8038 if (max_fits < best_fits)
8039 continue;
8040
8041 /*
8042 * Both don't fit performance hint (i.e. uclamp_min)
8043 * but best energy cpu has better capacity.
8044 */
8045 if ((max_fits < 0) &&
8046 (cpu_thermal_cap <= best_thermal_cap))
8047 continue;
8048
8049 cur_delta = compute_energy(&eenv, pd, cpus, p,
8050 max_spare_cap_cpu);
8051 /* CPU utilization has changed */
8052 if (cur_delta < base_energy)
8053 goto unlock;
8054 cur_delta -= base_energy;
8055
8056 /*
8057 * Both fit for the task but best energy cpu has lower
8058 * energy impact.
8059 */
8060 if ((max_fits > 0) && (best_fits > 0) &&
8061 (cur_delta >= best_delta))
8062 continue;
8063
8064 best_delta = cur_delta;
8065 best_energy_cpu = max_spare_cap_cpu;
8066 best_fits = max_fits;
8067 best_thermal_cap = cpu_thermal_cap;
8068 }
8069 }
8070 rcu_read_unlock();
8071
8072 if ((best_fits > prev_fits) ||
8073 ((best_fits > 0) && (best_delta < prev_delta)) ||
8074 ((best_fits < 0) && (best_thermal_cap > prev_thermal_cap)))
8075 target = best_energy_cpu;
8076
8077 return target;
8078
8079 unlock:
8080 rcu_read_unlock();
8081
8082 return target;
8083 }
8084
8085 /*
8086 * select_task_rq_fair: Select target runqueue for the waking task in domains
8087 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE,
8088 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
8089 *
8090 * Balances load by selecting the idlest CPU in the idlest group, or under
8091 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
8092 *
8093 * Returns the target CPU number.
8094 */
8095 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int wake_flags)8096 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags)
8097 {
8098 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
8099 struct sched_domain *tmp, *sd = NULL;
8100 int cpu = smp_processor_id();
8101 int new_cpu = prev_cpu;
8102 int want_affine = 0;
8103 /* SD_flags and WF_flags share the first nibble */
8104 int sd_flag = wake_flags & 0xF;
8105
8106 /*
8107 * required for stable ->cpus_allowed
8108 */
8109 lockdep_assert_held(&p->pi_lock);
8110 if (wake_flags & WF_TTWU) {
8111 record_wakee(p);
8112
8113 if ((wake_flags & WF_CURRENT_CPU) &&
8114 cpumask_test_cpu(cpu, p->cpus_ptr))
8115 return cpu;
8116
8117 if (sched_energy_enabled()) {
8118 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
8119 if (new_cpu >= 0)
8120 return new_cpu;
8121 new_cpu = prev_cpu;
8122 }
8123
8124 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
8125 }
8126
8127 rcu_read_lock();
8128 for_each_domain(cpu, tmp) {
8129 /*
8130 * If both 'cpu' and 'prev_cpu' are part of this domain,
8131 * cpu is a valid SD_WAKE_AFFINE target.
8132 */
8133 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
8134 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
8135 if (cpu != prev_cpu)
8136 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
8137
8138 sd = NULL; /* Prefer wake_affine over balance flags */
8139 break;
8140 }
8141
8142 /*
8143 * Usually only true for WF_EXEC and WF_FORK, as sched_domains
8144 * usually do not have SD_BALANCE_WAKE set. That means wakeup
8145 * will usually go to the fast path.
8146 */
8147 if (tmp->flags & sd_flag)
8148 sd = tmp;
8149 else if (!want_affine)
8150 break;
8151 }
8152
8153 if (unlikely(sd)) {
8154 /* Slow path */
8155 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
8156 } else if (wake_flags & WF_TTWU) { /* XXX always ? */
8157 /* Fast path */
8158 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
8159 }
8160 rcu_read_unlock();
8161
8162 return new_cpu;
8163 }
8164
8165 /*
8166 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
8167 * cfs_rq_of(p) references at time of call are still valid and identify the
8168 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
8169 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)8170 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
8171 {
8172 struct sched_entity *se = &p->se;
8173
8174 if (!task_on_rq_migrating(p)) {
8175 remove_entity_load_avg(se);
8176
8177 /*
8178 * Here, the task's PELT values have been updated according to
8179 * the current rq's clock. But if that clock hasn't been
8180 * updated in a while, a substantial idle time will be missed,
8181 * leading to an inflation after wake-up on the new rq.
8182 *
8183 * Estimate the missing time from the cfs_rq last_update_time
8184 * and update sched_avg to improve the PELT continuity after
8185 * migration.
8186 */
8187 migrate_se_pelt_lag(se);
8188 }
8189
8190 /* Tell new CPU we are migrated */
8191 se->avg.last_update_time = 0;
8192
8193 update_scan_period(p, new_cpu);
8194 }
8195
task_dead_fair(struct task_struct * p)8196 static void task_dead_fair(struct task_struct *p)
8197 {
8198 remove_entity_load_avg(&p->se);
8199 }
8200
8201 static int
balance_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8202 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8203 {
8204 if (rq->nr_running)
8205 return 1;
8206
8207 return newidle_balance(rq, rf) != 0;
8208 }
8209 #endif /* CONFIG_SMP */
8210
8211 #ifdef CONFIG_SCHED_LATENCY_NICE
wakeup_latency_gran(struct sched_entity * curr,struct sched_entity * se)8212 static long wakeup_latency_gran(struct sched_entity *curr, struct sched_entity *se)
8213 {
8214 int latency_weight = se->latency_weight;
8215 long thresh = sysctl_sched_latency;
8216
8217 /*
8218 * A positive latency weigth means that the sched_entity has latency
8219 * requirement that needs to be evaluated versus other entity.
8220 * Otherwise, use the latency weight to evaluate how much scheduling
8221 * delay is acceptable by se.
8222 */
8223 if ((se->latency_weight > 0) || (curr->latency_weight > 0))
8224 latency_weight -= curr->latency_weight;
8225
8226 if (!latency_weight)
8227 return 0;
8228
8229 if (sched_feat(GENTLE_FAIR_SLEEPERS))
8230 thresh >>= 1;
8231
8232 /*
8233 * Clamp the delta to stay in the scheduler period range
8234 * [-sysctl_sched_latency:sysctl_sched_latency]
8235 */
8236 latency_weight = clamp_t(long, latency_weight,
8237 -1 * NICE_LATENCY_WEIGHT_MAX,
8238 NICE_LATENCY_WEIGHT_MAX);
8239
8240 return (thresh * latency_weight) >> NICE_LATENCY_SHIFT;
8241 }
8242 #endif
8243
wakeup_gran(struct sched_entity * se)8244 static unsigned long wakeup_gran(struct sched_entity *se)
8245 {
8246 unsigned long gran = sysctl_sched_wakeup_granularity;
8247
8248 /*
8249 * Since its curr running now, convert the gran from real-time
8250 * to virtual-time in his units.
8251 *
8252 * By using 'se' instead of 'curr' we penalize light tasks, so
8253 * they get preempted easier. That is, if 'se' < 'curr' then
8254 * the resulting gran will be larger, therefore penalizing the
8255 * lighter, if otoh 'se' > 'curr' then the resulting gran will
8256 * be smaller, again penalizing the lighter task.
8257 *
8258 * This is especially important for buddies when the leftmost
8259 * task is higher priority than the buddy.
8260 */
8261 return calc_delta_fair(gran, se);
8262 }
8263
8264 /*
8265 * Should 'se' preempt 'curr'.
8266 *
8267 * |s1
8268 * |s2
8269 * |s3
8270 * g
8271 * |<--->|c
8272 *
8273 * w(c, s1) = -1
8274 * w(c, s2) = 0
8275 * w(c, s3) = 1
8276 *
8277 */
8278 static int
wakeup_preempt_entity(struct sched_entity * curr,struct sched_entity * se)8279 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
8280 {
8281 s64 gran, vdiff = curr->vruntime - se->vruntime;
8282
8283 #ifdef CONFIG_SCHED_LATENCY_NICE
8284 /* Take into account latency priority */
8285 vdiff += wakeup_latency_gran(curr, se);
8286 #endif
8287
8288 if (vdiff <= 0)
8289 return -1;
8290
8291 gran = wakeup_gran(se);
8292 if (vdiff > gran)
8293 return 1;
8294
8295 return 0;
8296 }
8297
set_next_buddy(struct sched_entity * se)8298 static void set_next_buddy(struct sched_entity *se)
8299 {
8300 for_each_sched_entity(se) {
8301 if (SCHED_WARN_ON(!se->on_rq))
8302 return;
8303 if (se_is_idle(se))
8304 return;
8305 cfs_rq_of(se)->next = se;
8306 }
8307 }
8308
8309 /*
8310 * Preempt the current task with a newly woken task if needed:
8311 */
check_preempt_wakeup(struct rq * rq,struct task_struct * p,int wake_flags)8312 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
8313 {
8314 struct task_struct *curr = rq->curr;
8315 struct sched_entity *se = &curr->se, *pse = &p->se;
8316 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8317 int next_buddy_marked = 0;
8318 int cse_is_idle, pse_is_idle;
8319
8320 if (unlikely(se == pse))
8321 return;
8322
8323 /*
8324 * This is possible from callers such as attach_tasks(), in which we
8325 * unconditionally check_preempt_curr() after an enqueue (which may have
8326 * lead to a throttle). This both saves work and prevents false
8327 * next-buddy nomination below.
8328 */
8329 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
8330 return;
8331
8332 if (sched_feat(NEXT_BUDDY) && !(wake_flags & WF_FORK)) {
8333 set_next_buddy(pse);
8334 next_buddy_marked = 1;
8335 }
8336
8337 /*
8338 * We can come here with TIF_NEED_RESCHED already set from new task
8339 * wake up path.
8340 *
8341 * Note: this also catches the edge-case of curr being in a throttled
8342 * group (e.g. via set_curr_task), since update_curr() (in the
8343 * enqueue of curr) will have resulted in resched being set. This
8344 * prevents us from potentially nominating it as a false LAST_BUDDY
8345 * below.
8346 */
8347 if (test_tsk_need_resched(curr))
8348 return;
8349
8350 /* Idle tasks are by definition preempted by non-idle tasks. */
8351 if (unlikely(task_has_idle_policy(curr)) &&
8352 likely(!task_has_idle_policy(p)))
8353 goto preempt;
8354
8355 /*
8356 * Batch and idle tasks do not preempt non-idle tasks (their preemption
8357 * is driven by the tick):
8358 */
8359 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
8360 return;
8361
8362 find_matching_se(&se, &pse);
8363 WARN_ON_ONCE(!pse);
8364
8365 cse_is_idle = se_is_idle(se);
8366 pse_is_idle = se_is_idle(pse);
8367
8368 /*
8369 * Preempt an idle group in favor of a non-idle group (and don't preempt
8370 * in the inverse case).
8371 */
8372 if (cse_is_idle && !pse_is_idle)
8373 goto preempt;
8374 if (cse_is_idle != pse_is_idle)
8375 return;
8376
8377 cfs_rq = cfs_rq_of(se);
8378 update_curr(cfs_rq);
8379
8380 /*
8381 * XXX pick_eevdf(cfs_rq) != se ?
8382 */
8383 if (pick_eevdf(cfs_rq) == pse)
8384 goto preempt;
8385
8386 return;
8387
8388 preempt:
8389 resched_curr(rq);
8390 }
8391
8392 #ifdef CONFIG_SMP
pick_task_fair(struct rq * rq)8393 static struct task_struct *pick_task_fair(struct rq *rq)
8394 {
8395 struct sched_entity *se;
8396 struct cfs_rq *cfs_rq;
8397
8398 again:
8399 cfs_rq = &rq->cfs;
8400 if (!cfs_rq->nr_running)
8401 return NULL;
8402
8403 do {
8404 struct sched_entity *curr = cfs_rq->curr;
8405
8406 /* When we pick for a remote RQ, we'll not have done put_prev_entity() */
8407 if (curr) {
8408 if (curr->on_rq)
8409 update_curr(cfs_rq);
8410 else
8411 curr = NULL;
8412
8413 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
8414 goto again;
8415 }
8416
8417 se = pick_next_entity(cfs_rq, curr);
8418 cfs_rq = group_cfs_rq(se);
8419 } while (cfs_rq);
8420
8421 return task_of(se);
8422 }
8423 #endif
8424
8425 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)8426 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
8427 {
8428 struct cfs_rq *cfs_rq = &rq->cfs;
8429 struct sched_entity *se;
8430 struct task_struct *p;
8431 int new_tasks;
8432
8433 again:
8434 if (!sched_fair_runnable(rq))
8435 goto idle;
8436
8437 #ifdef CONFIG_FAIR_GROUP_SCHED
8438 if (!prev || prev->sched_class != &fair_sched_class)
8439 goto simple;
8440
8441 /*
8442 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
8443 * likely that a next task is from the same cgroup as the current.
8444 *
8445 * Therefore attempt to avoid putting and setting the entire cgroup
8446 * hierarchy, only change the part that actually changes.
8447 */
8448
8449 do {
8450 struct sched_entity *curr = cfs_rq->curr;
8451
8452 /*
8453 * Since we got here without doing put_prev_entity() we also
8454 * have to consider cfs_rq->curr. If it is still a runnable
8455 * entity, update_curr() will update its vruntime, otherwise
8456 * forget we've ever seen it.
8457 */
8458 if (curr) {
8459 if (curr->on_rq)
8460 update_curr(cfs_rq);
8461 else
8462 curr = NULL;
8463
8464 /*
8465 * This call to check_cfs_rq_runtime() will do the
8466 * throttle and dequeue its entity in the parent(s).
8467 * Therefore the nr_running test will indeed
8468 * be correct.
8469 */
8470 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
8471 cfs_rq = &rq->cfs;
8472
8473 if (!cfs_rq->nr_running)
8474 goto idle;
8475
8476 goto simple;
8477 }
8478 }
8479
8480 se = pick_next_entity(cfs_rq, curr);
8481 cfs_rq = group_cfs_rq(se);
8482 } while (cfs_rq);
8483
8484 p = task_of(se);
8485
8486 /*
8487 * Since we haven't yet done put_prev_entity and if the selected task
8488 * is a different task than we started out with, try and touch the
8489 * least amount of cfs_rqs.
8490 */
8491 if (prev != p) {
8492 struct sched_entity *pse = &prev->se;
8493
8494 while (!(cfs_rq = is_same_group(se, pse))) {
8495 int se_depth = se->depth;
8496 int pse_depth = pse->depth;
8497
8498 if (se_depth <= pse_depth) {
8499 put_prev_entity(cfs_rq_of(pse), pse);
8500 pse = parent_entity(pse);
8501 }
8502 if (se_depth >= pse_depth) {
8503 set_next_entity(cfs_rq_of(se), se);
8504 se = parent_entity(se);
8505 }
8506 }
8507
8508 put_prev_entity(cfs_rq, pse);
8509 set_next_entity(cfs_rq, se);
8510 }
8511
8512 goto done;
8513 simple:
8514 #endif
8515 if (prev)
8516 put_prev_task(rq, prev);
8517
8518 do {
8519 se = pick_next_entity(cfs_rq, NULL);
8520 set_next_entity(cfs_rq, se);
8521 cfs_rq = group_cfs_rq(se);
8522 } while (cfs_rq);
8523
8524 p = task_of(se);
8525
8526 done: __maybe_unused;
8527 #ifdef CONFIG_SMP
8528 /*
8529 * Move the next running task to the front of
8530 * the list, so our cfs_tasks list becomes MRU
8531 * one.
8532 */
8533 list_move(&p->se.group_node, &rq->cfs_tasks);
8534 #endif
8535
8536 if (hrtick_enabled_fair(rq))
8537 hrtick_start_fair(rq, p);
8538
8539 update_misfit_status(p, rq);
8540 sched_fair_update_stop_tick(rq, p);
8541
8542 return p;
8543
8544 idle:
8545 if (!rf)
8546 return NULL;
8547
8548 new_tasks = newidle_balance(rq, rf);
8549
8550 /*
8551 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
8552 * possible for any higher priority task to appear. In that case we
8553 * must re-start the pick_next_entity() loop.
8554 */
8555 if (new_tasks < 0)
8556 return RETRY_TASK;
8557
8558 if (new_tasks > 0)
8559 goto again;
8560
8561 /*
8562 * rq is about to be idle, check if we need to update the
8563 * lost_idle_time of clock_pelt
8564 */
8565 update_idle_rq_clock_pelt(rq);
8566
8567 return NULL;
8568 }
8569
__pick_next_task_fair(struct rq * rq)8570 static struct task_struct *__pick_next_task_fair(struct rq *rq)
8571 {
8572 return pick_next_task_fair(rq, NULL, NULL);
8573 }
8574
8575 /*
8576 * Account for a descheduled task:
8577 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev)8578 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
8579 {
8580 struct sched_entity *se = &prev->se;
8581 struct cfs_rq *cfs_rq;
8582
8583 for_each_sched_entity(se) {
8584 cfs_rq = cfs_rq_of(se);
8585 put_prev_entity(cfs_rq, se);
8586 }
8587 }
8588
8589 /*
8590 * sched_yield() is very simple
8591 */
yield_task_fair(struct rq * rq)8592 static void yield_task_fair(struct rq *rq)
8593 {
8594 struct task_struct *curr = rq->curr;
8595 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
8596 struct sched_entity *se = &curr->se;
8597
8598 /*
8599 * Are we the only task in the tree?
8600 */
8601 if (unlikely(rq->nr_running == 1))
8602 return;
8603
8604 clear_buddies(cfs_rq, se);
8605
8606 update_rq_clock(rq);
8607 /*
8608 * Update run-time statistics of the 'current'.
8609 */
8610 update_curr(cfs_rq);
8611 /*
8612 * Tell update_rq_clock() that we've just updated,
8613 * so we don't do microscopic update in schedule()
8614 * and double the fastpath cost.
8615 */
8616 rq_clock_skip_update(rq);
8617
8618 se->deadline += calc_delta_fair(se->slice, se);
8619 }
8620
yield_to_task_fair(struct rq * rq,struct task_struct * p)8621 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
8622 {
8623 struct sched_entity *se = &p->se;
8624
8625 /* throttled hierarchies are not runnable */
8626 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
8627 return false;
8628
8629 /* Tell the scheduler that we'd really like pse to run next. */
8630 set_next_buddy(se);
8631
8632 yield_task_fair(rq);
8633
8634 return true;
8635 }
8636
8637 #ifdef CONFIG_SMP
8638 /**************************************************
8639 * Fair scheduling class load-balancing methods.
8640 *
8641 * BASICS
8642 *
8643 * The purpose of load-balancing is to achieve the same basic fairness the
8644 * per-CPU scheduler provides, namely provide a proportional amount of compute
8645 * time to each task. This is expressed in the following equation:
8646 *
8647 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
8648 *
8649 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
8650 * W_i,0 is defined as:
8651 *
8652 * W_i,0 = \Sum_j w_i,j (2)
8653 *
8654 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
8655 * is derived from the nice value as per sched_prio_to_weight[].
8656 *
8657 * The weight average is an exponential decay average of the instantaneous
8658 * weight:
8659 *
8660 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
8661 *
8662 * C_i is the compute capacity of CPU i, typically it is the
8663 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
8664 * can also include other factors [XXX].
8665 *
8666 * To achieve this balance we define a measure of imbalance which follows
8667 * directly from (1):
8668 *
8669 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
8670 *
8671 * We them move tasks around to minimize the imbalance. In the continuous
8672 * function space it is obvious this converges, in the discrete case we get
8673 * a few fun cases generally called infeasible weight scenarios.
8674 *
8675 * [XXX expand on:
8676 * - infeasible weights;
8677 * - local vs global optima in the discrete case. ]
8678 *
8679 *
8680 * SCHED DOMAINS
8681 *
8682 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
8683 * for all i,j solution, we create a tree of CPUs that follows the hardware
8684 * topology where each level pairs two lower groups (or better). This results
8685 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
8686 * tree to only the first of the previous level and we decrease the frequency
8687 * of load-balance at each level inv. proportional to the number of CPUs in
8688 * the groups.
8689 *
8690 * This yields:
8691 *
8692 * log_2 n 1 n
8693 * \Sum { --- * --- * 2^i } = O(n) (5)
8694 * i = 0 2^i 2^i
8695 * `- size of each group
8696 * | | `- number of CPUs doing load-balance
8697 * | `- freq
8698 * `- sum over all levels
8699 *
8700 * Coupled with a limit on how many tasks we can migrate every balance pass,
8701 * this makes (5) the runtime complexity of the balancer.
8702 *
8703 * An important property here is that each CPU is still (indirectly) connected
8704 * to every other CPU in at most O(log n) steps:
8705 *
8706 * The adjacency matrix of the resulting graph is given by:
8707 *
8708 * log_2 n
8709 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
8710 * k = 0
8711 *
8712 * And you'll find that:
8713 *
8714 * A^(log_2 n)_i,j != 0 for all i,j (7)
8715 *
8716 * Showing there's indeed a path between every CPU in at most O(log n) steps.
8717 * The task movement gives a factor of O(m), giving a convergence complexity
8718 * of:
8719 *
8720 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
8721 *
8722 *
8723 * WORK CONSERVING
8724 *
8725 * In order to avoid CPUs going idle while there's still work to do, new idle
8726 * balancing is more aggressive and has the newly idle CPU iterate up the domain
8727 * tree itself instead of relying on other CPUs to bring it work.
8728 *
8729 * This adds some complexity to both (5) and (8) but it reduces the total idle
8730 * time.
8731 *
8732 * [XXX more?]
8733 *
8734 *
8735 * CGROUPS
8736 *
8737 * Cgroups make a horror show out of (2), instead of a simple sum we get:
8738 *
8739 * s_k,i
8740 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
8741 * S_k
8742 *
8743 * Where
8744 *
8745 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
8746 *
8747 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
8748 *
8749 * The big problem is S_k, its a global sum needed to compute a local (W_i)
8750 * property.
8751 *
8752 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
8753 * rewrite all of this once again.]
8754 */
8755
8756 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
8757
8758 enum fbq_type { regular, remote, all };
8759
8760 /*
8761 * 'group_type' describes the group of CPUs at the moment of load balancing.
8762 *
8763 * The enum is ordered by pulling priority, with the group with lowest priority
8764 * first so the group_type can simply be compared when selecting the busiest
8765 * group. See update_sd_pick_busiest().
8766 */
8767 enum group_type {
8768 /* The group has spare capacity that can be used to run more tasks. */
8769 group_has_spare = 0,
8770 /*
8771 * The group is fully used and the tasks don't compete for more CPU
8772 * cycles. Nevertheless, some tasks might wait before running.
8773 */
8774 group_fully_busy,
8775 /*
8776 * One task doesn't fit with CPU's capacity and must be migrated to a
8777 * more powerful CPU.
8778 */
8779 group_misfit_task,
8780 /*
8781 * Balance SMT group that's fully busy. Can benefit from migration
8782 * a task on SMT with busy sibling to another CPU on idle core.
8783 */
8784 group_smt_balance,
8785 /*
8786 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
8787 * and the task should be migrated to it instead of running on the
8788 * current CPU.
8789 */
8790 group_asym_packing,
8791 /*
8792 * The tasks' affinity constraints previously prevented the scheduler
8793 * from balancing the load across the system.
8794 */
8795 group_imbalanced,
8796 /*
8797 * The CPU is overloaded and can't provide expected CPU cycles to all
8798 * tasks.
8799 */
8800 group_overloaded
8801 };
8802
8803 enum migration_type {
8804 migrate_load = 0,
8805 migrate_util,
8806 migrate_task,
8807 migrate_misfit
8808 };
8809
8810 #define LBF_ALL_PINNED 0x01
8811 #define LBF_NEED_BREAK 0x02
8812 #define LBF_DST_PINNED 0x04
8813 #define LBF_SOME_PINNED 0x08
8814 #define LBF_ACTIVE_LB 0x10
8815
8816 struct lb_env {
8817 struct sched_domain *sd;
8818
8819 struct rq *src_rq;
8820 int src_cpu;
8821
8822 int dst_cpu;
8823 struct rq *dst_rq;
8824
8825 struct cpumask *dst_grpmask;
8826 int new_dst_cpu;
8827 enum cpu_idle_type idle;
8828 long imbalance;
8829 /* The set of CPUs under consideration for load-balancing */
8830 struct cpumask *cpus;
8831
8832 unsigned int flags;
8833
8834 unsigned int loop;
8835 unsigned int loop_break;
8836 unsigned int loop_max;
8837
8838 enum fbq_type fbq_type;
8839 enum migration_type migration_type;
8840 struct list_head tasks;
8841 };
8842
8843 /*
8844 * Is this task likely cache-hot:
8845 */
task_hot(struct task_struct * p,struct lb_env * env)8846 static int task_hot(struct task_struct *p, struct lb_env *env)
8847 {
8848 s64 delta;
8849
8850 lockdep_assert_rq_held(env->src_rq);
8851
8852 if (p->sched_class != &fair_sched_class)
8853 return 0;
8854
8855 if (unlikely(task_has_idle_policy(p)))
8856 return 0;
8857
8858 /* SMT siblings share cache */
8859 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
8860 return 0;
8861
8862 /*
8863 * Buddy candidates are cache hot:
8864 */
8865 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
8866 (&p->se == cfs_rq_of(&p->se)->next))
8867 return 1;
8868
8869 if (sysctl_sched_migration_cost == -1)
8870 return 1;
8871
8872 /*
8873 * Don't migrate task if the task's cookie does not match
8874 * with the destination CPU's core cookie.
8875 */
8876 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p))
8877 return 1;
8878
8879 if (sysctl_sched_migration_cost == 0)
8880 return 0;
8881
8882 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
8883
8884 return delta < (s64)sysctl_sched_migration_cost;
8885 }
8886
8887 #ifdef CONFIG_NUMA_BALANCING
8888 /*
8889 * Returns 1, if task migration degrades locality
8890 * Returns 0, if task migration improves locality i.e migration preferred.
8891 * Returns -1, if task migration is not affected by locality.
8892 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)8893 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
8894 {
8895 struct numa_group *numa_group = rcu_dereference(p->numa_group);
8896 unsigned long src_weight, dst_weight;
8897 int src_nid, dst_nid, dist;
8898
8899 if (!static_branch_likely(&sched_numa_balancing))
8900 return -1;
8901
8902 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
8903 return -1;
8904
8905 src_nid = cpu_to_node(env->src_cpu);
8906 dst_nid = cpu_to_node(env->dst_cpu);
8907
8908 if (src_nid == dst_nid)
8909 return -1;
8910
8911 /* Migrating away from the preferred node is always bad. */
8912 if (src_nid == p->numa_preferred_nid) {
8913 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
8914 return 1;
8915 else
8916 return -1;
8917 }
8918
8919 /* Encourage migration to the preferred node. */
8920 if (dst_nid == p->numa_preferred_nid)
8921 return 0;
8922
8923 /* Leaving a core idle is often worse than degrading locality. */
8924 if (env->idle == CPU_IDLE)
8925 return -1;
8926
8927 dist = node_distance(src_nid, dst_nid);
8928 if (numa_group) {
8929 src_weight = group_weight(p, src_nid, dist);
8930 dst_weight = group_weight(p, dst_nid, dist);
8931 } else {
8932 src_weight = task_weight(p, src_nid, dist);
8933 dst_weight = task_weight(p, dst_nid, dist);
8934 }
8935
8936 return dst_weight < src_weight;
8937 }
8938
8939 #else
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)8940 static inline int migrate_degrades_locality(struct task_struct *p,
8941 struct lb_env *env)
8942 {
8943 return -1;
8944 }
8945 #endif
8946
8947 /*
8948 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
8949 */
8950 static
can_migrate_task(struct task_struct * p,struct lb_env * env)8951 int can_migrate_task(struct task_struct *p, struct lb_env *env)
8952 {
8953 int tsk_cache_hot;
8954
8955 lockdep_assert_rq_held(env->src_rq);
8956
8957 /*
8958 * We do not migrate tasks that are:
8959 * 1) throttled_lb_pair, or
8960 * 2) cannot be migrated to this CPU due to cpus_ptr, or
8961 * 3) running (obviously), or
8962 * 4) are cache-hot on their current CPU.
8963 */
8964 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
8965 return 0;
8966
8967 /* Disregard pcpu kthreads; they are where they need to be. */
8968 if (kthread_is_per_cpu(p))
8969 return 0;
8970
8971 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
8972 int cpu;
8973
8974 schedstat_inc(p->stats.nr_failed_migrations_affine);
8975
8976 env->flags |= LBF_SOME_PINNED;
8977
8978 /*
8979 * Remember if this task can be migrated to any other CPU in
8980 * our sched_group. We may want to revisit it if we couldn't
8981 * meet load balance goals by pulling other tasks on src_cpu.
8982 *
8983 * Avoid computing new_dst_cpu
8984 * - for NEWLY_IDLE
8985 * - if we have already computed one in current iteration
8986 * - if it's an active balance
8987 */
8988 if (env->idle == CPU_NEWLY_IDLE ||
8989 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB))
8990 return 0;
8991
8992 /* Prevent to re-select dst_cpu via env's CPUs: */
8993 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
8994 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
8995 env->flags |= LBF_DST_PINNED;
8996 env->new_dst_cpu = cpu;
8997 break;
8998 }
8999 }
9000
9001 return 0;
9002 }
9003
9004 /* Record that we found at least one task that could run on dst_cpu */
9005 env->flags &= ~LBF_ALL_PINNED;
9006
9007 if (task_on_cpu(env->src_rq, p)) {
9008 schedstat_inc(p->stats.nr_failed_migrations_running);
9009 return 0;
9010 }
9011
9012 /*
9013 * Aggressive migration if:
9014 * 1) active balance
9015 * 2) destination numa is preferred
9016 * 3) task is cache cold, or
9017 * 4) too many balance attempts have failed.
9018 */
9019 if (env->flags & LBF_ACTIVE_LB)
9020 return 1;
9021
9022 tsk_cache_hot = migrate_degrades_locality(p, env);
9023 if (tsk_cache_hot == -1)
9024 tsk_cache_hot = task_hot(p, env);
9025
9026 if (tsk_cache_hot <= 0 ||
9027 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
9028 if (tsk_cache_hot == 1) {
9029 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
9030 schedstat_inc(p->stats.nr_forced_migrations);
9031 }
9032 return 1;
9033 }
9034
9035 schedstat_inc(p->stats.nr_failed_migrations_hot);
9036 return 0;
9037 }
9038
9039 /*
9040 * detach_task() -- detach the task for the migration specified in env
9041 */
detach_task(struct task_struct * p,struct lb_env * env)9042 static void detach_task(struct task_struct *p, struct lb_env *env)
9043 {
9044 lockdep_assert_rq_held(env->src_rq);
9045
9046 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
9047 set_task_cpu(p, env->dst_cpu);
9048 }
9049
9050 /*
9051 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
9052 * part of active balancing operations within "domain".
9053 *
9054 * Returns a task if successful and NULL otherwise.
9055 */
detach_one_task(struct lb_env * env)9056 static struct task_struct *detach_one_task(struct lb_env *env)
9057 {
9058 struct task_struct *p;
9059
9060 lockdep_assert_rq_held(env->src_rq);
9061
9062 list_for_each_entry_reverse(p,
9063 &env->src_rq->cfs_tasks, se.group_node) {
9064 if (!can_migrate_task(p, env))
9065 continue;
9066
9067 detach_task(p, env);
9068
9069 /*
9070 * Right now, this is only the second place where
9071 * lb_gained[env->idle] is updated (other is detach_tasks)
9072 * so we can safely collect stats here rather than
9073 * inside detach_tasks().
9074 */
9075 schedstat_inc(env->sd->lb_gained[env->idle]);
9076 return p;
9077 }
9078 return NULL;
9079 }
9080
9081 /*
9082 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
9083 * busiest_rq, as part of a balancing operation within domain "sd".
9084 *
9085 * Returns number of detached tasks if successful and 0 otherwise.
9086 */
detach_tasks(struct lb_env * env)9087 static int detach_tasks(struct lb_env *env)
9088 {
9089 struct list_head *tasks = &env->src_rq->cfs_tasks;
9090 unsigned long util, load;
9091 struct task_struct *p;
9092 int detached = 0;
9093
9094 lockdep_assert_rq_held(env->src_rq);
9095
9096 /*
9097 * Source run queue has been emptied by another CPU, clear
9098 * LBF_ALL_PINNED flag as we will not test any task.
9099 */
9100 if (env->src_rq->nr_running <= 1) {
9101 env->flags &= ~LBF_ALL_PINNED;
9102 return 0;
9103 }
9104
9105 if (env->imbalance <= 0)
9106 return 0;
9107
9108 while (!list_empty(tasks)) {
9109 /*
9110 * We don't want to steal all, otherwise we may be treated likewise,
9111 * which could at worst lead to a livelock crash.
9112 */
9113 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
9114 break;
9115
9116 env->loop++;
9117 /*
9118 * We've more or less seen every task there is, call it quits
9119 * unless we haven't found any movable task yet.
9120 */
9121 if (env->loop > env->loop_max &&
9122 !(env->flags & LBF_ALL_PINNED))
9123 break;
9124
9125 /* take a breather every nr_migrate tasks */
9126 if (env->loop > env->loop_break) {
9127 env->loop_break += SCHED_NR_MIGRATE_BREAK;
9128 env->flags |= LBF_NEED_BREAK;
9129 break;
9130 }
9131
9132 p = list_last_entry(tasks, struct task_struct, se.group_node);
9133
9134 if (!can_migrate_task(p, env))
9135 goto next;
9136
9137 switch (env->migration_type) {
9138 case migrate_load:
9139 /*
9140 * Depending of the number of CPUs and tasks and the
9141 * cgroup hierarchy, task_h_load() can return a null
9142 * value. Make sure that env->imbalance decreases
9143 * otherwise detach_tasks() will stop only after
9144 * detaching up to loop_max tasks.
9145 */
9146 load = max_t(unsigned long, task_h_load(p), 1);
9147
9148 if (sched_feat(LB_MIN) &&
9149 load < 16 && !env->sd->nr_balance_failed)
9150 goto next;
9151
9152 /*
9153 * Make sure that we don't migrate too much load.
9154 * Nevertheless, let relax the constraint if
9155 * scheduler fails to find a good waiting task to
9156 * migrate.
9157 */
9158 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
9159 goto next;
9160
9161 env->imbalance -= load;
9162 break;
9163
9164 case migrate_util:
9165 util = task_util_est(p);
9166
9167 if (util > env->imbalance)
9168 goto next;
9169
9170 env->imbalance -= util;
9171 break;
9172
9173 case migrate_task:
9174 env->imbalance--;
9175 break;
9176
9177 case migrate_misfit:
9178 /* This is not a misfit task */
9179 if (task_fits_cpu(p, env->src_cpu))
9180 goto next;
9181
9182 env->imbalance = 0;
9183 break;
9184 }
9185
9186 detach_task(p, env);
9187 list_add(&p->se.group_node, &env->tasks);
9188
9189 detached++;
9190
9191 #ifdef CONFIG_PREEMPTION
9192 /*
9193 * NEWIDLE balancing is a source of latency, so preemptible
9194 * kernels will stop after the first task is detached to minimize
9195 * the critical section.
9196 */
9197 if (env->idle == CPU_NEWLY_IDLE)
9198 break;
9199 #endif
9200
9201 /*
9202 * We only want to steal up to the prescribed amount of
9203 * load/util/tasks.
9204 */
9205 if (env->imbalance <= 0)
9206 break;
9207
9208 continue;
9209 next:
9210 list_move(&p->se.group_node, tasks);
9211 }
9212
9213 /*
9214 * Right now, this is one of only two places we collect this stat
9215 * so we can safely collect detach_one_task() stats here rather
9216 * than inside detach_one_task().
9217 */
9218 schedstat_add(env->sd->lb_gained[env->idle], detached);
9219
9220 return detached;
9221 }
9222
9223 /*
9224 * attach_task() -- attach the task detached by detach_task() to its new rq.
9225 */
attach_task(struct rq * rq,struct task_struct * p)9226 static void attach_task(struct rq *rq, struct task_struct *p)
9227 {
9228 lockdep_assert_rq_held(rq);
9229
9230 WARN_ON_ONCE(task_rq(p) != rq);
9231 activate_task(rq, p, ENQUEUE_NOCLOCK);
9232 check_preempt_curr(rq, p, 0);
9233 }
9234
9235 /*
9236 * attach_one_task() -- attaches the task returned from detach_one_task() to
9237 * its new rq.
9238 */
attach_one_task(struct rq * rq,struct task_struct * p)9239 static void attach_one_task(struct rq *rq, struct task_struct *p)
9240 {
9241 struct rq_flags rf;
9242
9243 rq_lock(rq, &rf);
9244 update_rq_clock(rq);
9245 attach_task(rq, p);
9246 rq_unlock(rq, &rf);
9247 }
9248
9249 /*
9250 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
9251 * new rq.
9252 */
attach_tasks(struct lb_env * env)9253 static void attach_tasks(struct lb_env *env)
9254 {
9255 struct list_head *tasks = &env->tasks;
9256 struct task_struct *p;
9257 struct rq_flags rf;
9258
9259 rq_lock(env->dst_rq, &rf);
9260 update_rq_clock(env->dst_rq);
9261
9262 while (!list_empty(tasks)) {
9263 p = list_first_entry(tasks, struct task_struct, se.group_node);
9264 list_del_init(&p->se.group_node);
9265
9266 attach_task(env->dst_rq, p);
9267 }
9268
9269 rq_unlock(env->dst_rq, &rf);
9270 }
9271
9272 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9273 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
9274 {
9275 if (cfs_rq->avg.load_avg)
9276 return true;
9277
9278 if (cfs_rq->avg.util_avg)
9279 return true;
9280
9281 return false;
9282 }
9283
others_have_blocked(struct rq * rq)9284 static inline bool others_have_blocked(struct rq *rq)
9285 {
9286 if (READ_ONCE(rq->avg_rt.util_avg))
9287 return true;
9288
9289 if (READ_ONCE(rq->avg_dl.util_avg))
9290 return true;
9291
9292 if (thermal_load_avg(rq))
9293 return true;
9294
9295 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
9296 if (READ_ONCE(rq->avg_irq.util_avg))
9297 return true;
9298 #endif
9299
9300 return false;
9301 }
9302
update_blocked_load_tick(struct rq * rq)9303 static inline void update_blocked_load_tick(struct rq *rq)
9304 {
9305 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies);
9306 }
9307
update_blocked_load_status(struct rq * rq,bool has_blocked)9308 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
9309 {
9310 if (!has_blocked)
9311 rq->has_blocked_load = 0;
9312 }
9313 #else
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)9314 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)9315 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_tick(struct rq * rq)9316 static inline void update_blocked_load_tick(struct rq *rq) {}
update_blocked_load_status(struct rq * rq,bool has_blocked)9317 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
9318 #endif
9319
__update_blocked_others(struct rq * rq,bool * done)9320 static bool __update_blocked_others(struct rq *rq, bool *done)
9321 {
9322 const struct sched_class *curr_class;
9323 u64 now = rq_clock_pelt(rq);
9324 unsigned long thermal_pressure;
9325 bool decayed;
9326
9327 /*
9328 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
9329 * DL and IRQ signals have been updated before updating CFS.
9330 */
9331 curr_class = rq->curr->sched_class;
9332
9333 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
9334
9335 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
9336 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
9337 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
9338 update_irq_load_avg(rq, 0);
9339
9340 if (others_have_blocked(rq))
9341 *done = false;
9342
9343 return decayed;
9344 }
9345
9346 #ifdef CONFIG_FAIR_GROUP_SCHED
9347
__update_blocked_fair(struct rq * rq,bool * done)9348 static bool __update_blocked_fair(struct rq *rq, bool *done)
9349 {
9350 struct cfs_rq *cfs_rq, *pos;
9351 bool decayed = false;
9352 int cpu = cpu_of(rq);
9353
9354 /*
9355 * Iterates the task_group tree in a bottom up fashion, see
9356 * list_add_leaf_cfs_rq() for details.
9357 */
9358 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
9359 struct sched_entity *se;
9360
9361 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
9362 update_tg_load_avg(cfs_rq);
9363
9364 if (cfs_rq->nr_running == 0)
9365 update_idle_cfs_rq_clock_pelt(cfs_rq);
9366
9367 if (cfs_rq == &rq->cfs)
9368 decayed = true;
9369 }
9370
9371 /* Propagate pending load changes to the parent, if any: */
9372 se = cfs_rq->tg->se[cpu];
9373 if (se && !skip_blocked_update(se))
9374 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
9375
9376 /*
9377 * There can be a lot of idle CPU cgroups. Don't let fully
9378 * decayed cfs_rqs linger on the list.
9379 */
9380 if (cfs_rq_is_decayed(cfs_rq))
9381 list_del_leaf_cfs_rq(cfs_rq);
9382
9383 /* Don't need periodic decay once load/util_avg are null */
9384 if (cfs_rq_has_blocked(cfs_rq))
9385 *done = false;
9386 }
9387
9388 return decayed;
9389 }
9390
9391 /*
9392 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
9393 * This needs to be done in a top-down fashion because the load of a child
9394 * group is a fraction of its parents load.
9395 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)9396 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
9397 {
9398 struct rq *rq = rq_of(cfs_rq);
9399 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
9400 unsigned long now = jiffies;
9401 unsigned long load;
9402
9403 if (cfs_rq->last_h_load_update == now)
9404 return;
9405
9406 WRITE_ONCE(cfs_rq->h_load_next, NULL);
9407 for_each_sched_entity(se) {
9408 cfs_rq = cfs_rq_of(se);
9409 WRITE_ONCE(cfs_rq->h_load_next, se);
9410 if (cfs_rq->last_h_load_update == now)
9411 break;
9412 }
9413
9414 if (!se) {
9415 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
9416 cfs_rq->last_h_load_update = now;
9417 }
9418
9419 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
9420 load = cfs_rq->h_load;
9421 load = div64_ul(load * se->avg.load_avg,
9422 cfs_rq_load_avg(cfs_rq) + 1);
9423 cfs_rq = group_cfs_rq(se);
9424 cfs_rq->h_load = load;
9425 cfs_rq->last_h_load_update = now;
9426 }
9427 }
9428
task_h_load(struct task_struct * p)9429 static unsigned long task_h_load(struct task_struct *p)
9430 {
9431 struct cfs_rq *cfs_rq = task_cfs_rq(p);
9432
9433 update_cfs_rq_h_load(cfs_rq);
9434 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
9435 cfs_rq_load_avg(cfs_rq) + 1);
9436 }
9437 #else
__update_blocked_fair(struct rq * rq,bool * done)9438 static bool __update_blocked_fair(struct rq *rq, bool *done)
9439 {
9440 struct cfs_rq *cfs_rq = &rq->cfs;
9441 bool decayed;
9442
9443 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
9444 if (cfs_rq_has_blocked(cfs_rq))
9445 *done = false;
9446
9447 return decayed;
9448 }
9449
task_h_load(struct task_struct * p)9450 static unsigned long task_h_load(struct task_struct *p)
9451 {
9452 return p->se.avg.load_avg;
9453 }
9454 #endif
9455
update_blocked_averages(int cpu)9456 static void update_blocked_averages(int cpu)
9457 {
9458 bool decayed = false, done = true;
9459 struct rq *rq = cpu_rq(cpu);
9460 struct rq_flags rf;
9461
9462 rq_lock_irqsave(rq, &rf);
9463 update_blocked_load_tick(rq);
9464 update_rq_clock(rq);
9465
9466 decayed |= __update_blocked_others(rq, &done);
9467 decayed |= __update_blocked_fair(rq, &done);
9468
9469 update_blocked_load_status(rq, !done);
9470 if (decayed)
9471 cpufreq_update_util(rq, 0);
9472 rq_unlock_irqrestore(rq, &rf);
9473 }
9474
9475 /********** Helpers for find_busiest_group ************************/
9476
9477 /*
9478 * sg_lb_stats - stats of a sched_group required for load_balancing
9479 */
9480 struct sg_lb_stats {
9481 unsigned long avg_load; /*Avg load across the CPUs of the group */
9482 unsigned long group_load; /* Total load over the CPUs of the group */
9483 unsigned long group_capacity;
9484 unsigned long group_util; /* Total utilization over the CPUs of the group */
9485 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
9486 unsigned int sum_nr_running; /* Nr of tasks running in the group */
9487 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
9488 unsigned int idle_cpus;
9489 unsigned int group_weight;
9490 enum group_type group_type;
9491 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
9492 unsigned int group_smt_balance; /* Task on busy SMT be moved */
9493 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
9494 #ifdef CONFIG_NUMA_BALANCING
9495 unsigned int nr_numa_running;
9496 unsigned int nr_preferred_running;
9497 #endif
9498 };
9499
9500 /*
9501 * sd_lb_stats - Structure to store the statistics of a sched_domain
9502 * during load balancing.
9503 */
9504 struct sd_lb_stats {
9505 struct sched_group *busiest; /* Busiest group in this sd */
9506 struct sched_group *local; /* Local group in this sd */
9507 unsigned long total_load; /* Total load of all groups in sd */
9508 unsigned long total_capacity; /* Total capacity of all groups in sd */
9509 unsigned long avg_load; /* Average load across all groups in sd */
9510 unsigned int prefer_sibling; /* tasks should go to sibling first */
9511
9512 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
9513 struct sg_lb_stats local_stat; /* Statistics of the local group */
9514 };
9515
init_sd_lb_stats(struct sd_lb_stats * sds)9516 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
9517 {
9518 /*
9519 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
9520 * local_stat because update_sg_lb_stats() does a full clear/assignment.
9521 * We must however set busiest_stat::group_type and
9522 * busiest_stat::idle_cpus to the worst busiest group because
9523 * update_sd_pick_busiest() reads these before assignment.
9524 */
9525 *sds = (struct sd_lb_stats){
9526 .busiest = NULL,
9527 .local = NULL,
9528 .total_load = 0UL,
9529 .total_capacity = 0UL,
9530 .busiest_stat = {
9531 .idle_cpus = UINT_MAX,
9532 .group_type = group_has_spare,
9533 },
9534 };
9535 }
9536
scale_rt_capacity(int cpu)9537 static unsigned long scale_rt_capacity(int cpu)
9538 {
9539 struct rq *rq = cpu_rq(cpu);
9540 unsigned long max = arch_scale_cpu_capacity(cpu);
9541 unsigned long used, free;
9542 unsigned long irq;
9543
9544 irq = cpu_util_irq(rq);
9545
9546 if (unlikely(irq >= max))
9547 return 1;
9548
9549 /*
9550 * avg_rt.util_avg and avg_dl.util_avg track binary signals
9551 * (running and not running) with weights 0 and 1024 respectively.
9552 * avg_thermal.load_avg tracks thermal pressure and the weighted
9553 * average uses the actual delta max capacity(load).
9554 */
9555 used = READ_ONCE(rq->avg_rt.util_avg);
9556 used += READ_ONCE(rq->avg_dl.util_avg);
9557 used += thermal_load_avg(rq);
9558
9559 if (unlikely(used >= max))
9560 return 1;
9561
9562 free = max - used;
9563
9564 return scale_irq_capacity(free, irq, max);
9565 }
9566
update_cpu_capacity(struct sched_domain * sd,int cpu)9567 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
9568 {
9569 unsigned long capacity = scale_rt_capacity(cpu);
9570 struct sched_group *sdg = sd->groups;
9571
9572 cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
9573
9574 if (!capacity)
9575 capacity = 1;
9576
9577 cpu_rq(cpu)->cpu_capacity = capacity;
9578 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
9579
9580 sdg->sgc->capacity = capacity;
9581 sdg->sgc->min_capacity = capacity;
9582 sdg->sgc->max_capacity = capacity;
9583 }
9584
update_group_capacity(struct sched_domain * sd,int cpu)9585 void update_group_capacity(struct sched_domain *sd, int cpu)
9586 {
9587 struct sched_domain *child = sd->child;
9588 struct sched_group *group, *sdg = sd->groups;
9589 unsigned long capacity, min_capacity, max_capacity;
9590 unsigned long interval;
9591
9592 interval = msecs_to_jiffies(sd->balance_interval);
9593 interval = clamp(interval, 1UL, max_load_balance_interval);
9594 sdg->sgc->next_update = jiffies + interval;
9595
9596 if (!child) {
9597 update_cpu_capacity(sd, cpu);
9598 return;
9599 }
9600
9601 capacity = 0;
9602 min_capacity = ULONG_MAX;
9603 max_capacity = 0;
9604
9605 if (child->flags & SD_OVERLAP) {
9606 /*
9607 * SD_OVERLAP domains cannot assume that child groups
9608 * span the current group.
9609 */
9610
9611 for_each_cpu(cpu, sched_group_span(sdg)) {
9612 unsigned long cpu_cap = capacity_of(cpu);
9613
9614 capacity += cpu_cap;
9615 min_capacity = min(cpu_cap, min_capacity);
9616 max_capacity = max(cpu_cap, max_capacity);
9617 }
9618 } else {
9619 /*
9620 * !SD_OVERLAP domains can assume that child groups
9621 * span the current group.
9622 */
9623
9624 group = child->groups;
9625 do {
9626 struct sched_group_capacity *sgc = group->sgc;
9627
9628 capacity += sgc->capacity;
9629 min_capacity = min(sgc->min_capacity, min_capacity);
9630 max_capacity = max(sgc->max_capacity, max_capacity);
9631 group = group->next;
9632 } while (group != child->groups);
9633 }
9634
9635 sdg->sgc->capacity = capacity;
9636 sdg->sgc->min_capacity = min_capacity;
9637 sdg->sgc->max_capacity = max_capacity;
9638 }
9639
9640 /*
9641 * Check whether the capacity of the rq has been noticeably reduced by side
9642 * activity. The imbalance_pct is used for the threshold.
9643 * Return true is the capacity is reduced
9644 */
9645 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)9646 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
9647 {
9648 return ((rq->cpu_capacity * sd->imbalance_pct) <
9649 (rq->cpu_capacity_orig * 100));
9650 }
9651
9652 /*
9653 * Check whether a rq has a misfit task and if it looks like we can actually
9654 * help that task: we can migrate the task to a CPU of higher capacity, or
9655 * the task's current CPU is heavily pressured.
9656 */
check_misfit_status(struct rq * rq,struct sched_domain * sd)9657 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
9658 {
9659 return rq->misfit_task_load &&
9660 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
9661 check_cpu_capacity(rq, sd));
9662 }
9663
9664 /*
9665 * Group imbalance indicates (and tries to solve) the problem where balancing
9666 * groups is inadequate due to ->cpus_ptr constraints.
9667 *
9668 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
9669 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
9670 * Something like:
9671 *
9672 * { 0 1 2 3 } { 4 5 6 7 }
9673 * * * * *
9674 *
9675 * If we were to balance group-wise we'd place two tasks in the first group and
9676 * two tasks in the second group. Clearly this is undesired as it will overload
9677 * cpu 3 and leave one of the CPUs in the second group unused.
9678 *
9679 * The current solution to this issue is detecting the skew in the first group
9680 * by noticing the lower domain failed to reach balance and had difficulty
9681 * moving tasks due to affinity constraints.
9682 *
9683 * When this is so detected; this group becomes a candidate for busiest; see
9684 * update_sd_pick_busiest(). And calculate_imbalance() and
9685 * find_busiest_group() avoid some of the usual balance conditions to allow it
9686 * to create an effective group imbalance.
9687 *
9688 * This is a somewhat tricky proposition since the next run might not find the
9689 * group imbalance and decide the groups need to be balanced again. A most
9690 * subtle and fragile situation.
9691 */
9692
sg_imbalanced(struct sched_group * group)9693 static inline int sg_imbalanced(struct sched_group *group)
9694 {
9695 return group->sgc->imbalance;
9696 }
9697
9698 /*
9699 * group_has_capacity returns true if the group has spare capacity that could
9700 * be used by some tasks.
9701 * We consider that a group has spare capacity if the number of task is
9702 * smaller than the number of CPUs or if the utilization is lower than the
9703 * available capacity for CFS tasks.
9704 * For the latter, we use a threshold to stabilize the state, to take into
9705 * account the variance of the tasks' load and to return true if the available
9706 * capacity in meaningful for the load balancer.
9707 * As an example, an available capacity of 1% can appear but it doesn't make
9708 * any benefit for the load balance.
9709 */
9710 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)9711 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9712 {
9713 if (sgs->sum_nr_running < sgs->group_weight)
9714 return true;
9715
9716 if ((sgs->group_capacity * imbalance_pct) <
9717 (sgs->group_runnable * 100))
9718 return false;
9719
9720 if ((sgs->group_capacity * 100) >
9721 (sgs->group_util * imbalance_pct))
9722 return true;
9723
9724 return false;
9725 }
9726
9727 /*
9728 * group_is_overloaded returns true if the group has more tasks than it can
9729 * handle.
9730 * group_is_overloaded is not equals to !group_has_capacity because a group
9731 * with the exact right number of tasks, has no more spare capacity but is not
9732 * overloaded so both group_has_capacity and group_is_overloaded return
9733 * false.
9734 */
9735 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)9736 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
9737 {
9738 if (sgs->sum_nr_running <= sgs->group_weight)
9739 return false;
9740
9741 if ((sgs->group_capacity * 100) <
9742 (sgs->group_util * imbalance_pct))
9743 return true;
9744
9745 if ((sgs->group_capacity * imbalance_pct) <
9746 (sgs->group_runnable * 100))
9747 return true;
9748
9749 return false;
9750 }
9751
9752 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)9753 group_type group_classify(unsigned int imbalance_pct,
9754 struct sched_group *group,
9755 struct sg_lb_stats *sgs)
9756 {
9757 if (group_is_overloaded(imbalance_pct, sgs))
9758 return group_overloaded;
9759
9760 if (sg_imbalanced(group))
9761 return group_imbalanced;
9762
9763 if (sgs->group_asym_packing)
9764 return group_asym_packing;
9765
9766 if (sgs->group_smt_balance)
9767 return group_smt_balance;
9768
9769 if (sgs->group_misfit_task_load)
9770 return group_misfit_task;
9771
9772 if (!group_has_capacity(imbalance_pct, sgs))
9773 return group_fully_busy;
9774
9775 return group_has_spare;
9776 }
9777
9778 /**
9779 * sched_use_asym_prio - Check whether asym_packing priority must be used
9780 * @sd: The scheduling domain of the load balancing
9781 * @cpu: A CPU
9782 *
9783 * Always use CPU priority when balancing load between SMT siblings. When
9784 * balancing load between cores, it is not sufficient that @cpu is idle. Only
9785 * use CPU priority if the whole core is idle.
9786 *
9787 * Returns: True if the priority of @cpu must be followed. False otherwise.
9788 */
sched_use_asym_prio(struct sched_domain * sd,int cpu)9789 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu)
9790 {
9791 if (!sched_smt_active())
9792 return true;
9793
9794 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu);
9795 }
9796
9797 /**
9798 * sched_asym - Check if the destination CPU can do asym_packing load balance
9799 * @env: The load balancing environment
9800 * @sds: Load-balancing data with statistics of the local group
9801 * @sgs: Load-balancing statistics of the candidate busiest group
9802 * @group: The candidate busiest group
9803 *
9804 * @env::dst_cpu can do asym_packing if it has higher priority than the
9805 * preferred CPU of @group.
9806 *
9807 * SMT is a special case. If we are balancing load between cores, @env::dst_cpu
9808 * can do asym_packing balance only if all its SMT siblings are idle. Also, it
9809 * can only do it if @group is an SMT group and has exactly on busy CPU. Larger
9810 * imbalances in the number of CPUS are dealt with in find_busiest_group().
9811 *
9812 * If we are balancing load within an SMT core, or at DIE domain level, always
9813 * proceed.
9814 *
9815 * Return: true if @env::dst_cpu can do with asym_packing load balance. False
9816 * otherwise.
9817 */
9818 static inline bool
sched_asym(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * sgs,struct sched_group * group)9819 sched_asym(struct lb_env *env, struct sd_lb_stats *sds, struct sg_lb_stats *sgs,
9820 struct sched_group *group)
9821 {
9822 /* Ensure that the whole local core is idle, if applicable. */
9823 if (!sched_use_asym_prio(env->sd, env->dst_cpu))
9824 return false;
9825
9826 /*
9827 * CPU priorities does not make sense for SMT cores with more than one
9828 * busy sibling.
9829 */
9830 if (group->flags & SD_SHARE_CPUCAPACITY) {
9831 if (sgs->group_weight - sgs->idle_cpus != 1)
9832 return false;
9833 }
9834
9835 return sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu);
9836 }
9837
9838 /* 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)9839 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1,
9840 struct sched_group *sg2)
9841 {
9842 if (!sg1 || !sg2)
9843 return false;
9844
9845 return (sg1->flags & SD_SHARE_CPUCAPACITY) !=
9846 (sg2->flags & SD_SHARE_CPUCAPACITY);
9847 }
9848
smt_balance(struct lb_env * env,struct sg_lb_stats * sgs,struct sched_group * group)9849 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs,
9850 struct sched_group *group)
9851 {
9852 if (env->idle == CPU_NOT_IDLE)
9853 return false;
9854
9855 /*
9856 * For SMT source group, it is better to move a task
9857 * to a CPU that doesn't have multiple tasks sharing its CPU capacity.
9858 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY
9859 * will not be on.
9860 */
9861 if (group->flags & SD_SHARE_CPUCAPACITY &&
9862 sgs->sum_h_nr_running > 1)
9863 return true;
9864
9865 return false;
9866 }
9867
sibling_imbalance(struct lb_env * env,struct sd_lb_stats * sds,struct sg_lb_stats * busiest,struct sg_lb_stats * local)9868 static inline long sibling_imbalance(struct lb_env *env,
9869 struct sd_lb_stats *sds,
9870 struct sg_lb_stats *busiest,
9871 struct sg_lb_stats *local)
9872 {
9873 int ncores_busiest, ncores_local;
9874 long imbalance;
9875
9876 if (env->idle == CPU_NOT_IDLE || !busiest->sum_nr_running)
9877 return 0;
9878
9879 ncores_busiest = sds->busiest->cores;
9880 ncores_local = sds->local->cores;
9881
9882 if (ncores_busiest == ncores_local) {
9883 imbalance = busiest->sum_nr_running;
9884 lsub_positive(&imbalance, local->sum_nr_running);
9885 return imbalance;
9886 }
9887
9888 /* Balance such that nr_running/ncores ratio are same on both groups */
9889 imbalance = ncores_local * busiest->sum_nr_running;
9890 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running);
9891 /* Normalize imbalance and do rounding on normalization */
9892 imbalance = 2 * imbalance + ncores_local + ncores_busiest;
9893 imbalance /= ncores_local + ncores_busiest;
9894
9895 /* Take advantage of resource in an empty sched group */
9896 if (imbalance <= 1 && local->sum_nr_running == 0 &&
9897 busiest->sum_nr_running > 1)
9898 imbalance = 2;
9899
9900 return imbalance;
9901 }
9902
9903 static inline bool
sched_reduced_capacity(struct rq * rq,struct sched_domain * sd)9904 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd)
9905 {
9906 /*
9907 * When there is more than 1 task, the group_overloaded case already
9908 * takes care of cpu with reduced capacity
9909 */
9910 if (rq->cfs.h_nr_running != 1)
9911 return false;
9912
9913 return check_cpu_capacity(rq, sd);
9914 }
9915
9916 /**
9917 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
9918 * @env: The load balancing environment.
9919 * @sds: Load-balancing data with statistics of the local group.
9920 * @group: sched_group whose statistics are to be updated.
9921 * @sgs: variable to hold the statistics for this group.
9922 * @sg_status: Holds flag indicating the status of the sched_group
9923 */
update_sg_lb_stats(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * group,struct sg_lb_stats * sgs,int * sg_status)9924 static inline void update_sg_lb_stats(struct lb_env *env,
9925 struct sd_lb_stats *sds,
9926 struct sched_group *group,
9927 struct sg_lb_stats *sgs,
9928 int *sg_status)
9929 {
9930 int i, nr_running, local_group;
9931
9932 memset(sgs, 0, sizeof(*sgs));
9933
9934 local_group = group == sds->local;
9935
9936 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9937 struct rq *rq = cpu_rq(i);
9938 unsigned long load = cpu_load(rq);
9939
9940 sgs->group_load += load;
9941 sgs->group_util += cpu_util_cfs(i);
9942 sgs->group_runnable += cpu_runnable(rq);
9943 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
9944
9945 nr_running = rq->nr_running;
9946 sgs->sum_nr_running += nr_running;
9947
9948 if (nr_running > 1)
9949 *sg_status |= SG_OVERLOAD;
9950
9951 if (cpu_overutilized(i))
9952 *sg_status |= SG_OVERUTILIZED;
9953
9954 #ifdef CONFIG_NUMA_BALANCING
9955 sgs->nr_numa_running += rq->nr_numa_running;
9956 sgs->nr_preferred_running += rq->nr_preferred_running;
9957 #endif
9958 /*
9959 * No need to call idle_cpu() if nr_running is not 0
9960 */
9961 if (!nr_running && idle_cpu(i)) {
9962 sgs->idle_cpus++;
9963 /* Idle cpu can't have misfit task */
9964 continue;
9965 }
9966
9967 if (local_group)
9968 continue;
9969
9970 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
9971 /* Check for a misfit task on the cpu */
9972 if (sgs->group_misfit_task_load < rq->misfit_task_load) {
9973 sgs->group_misfit_task_load = rq->misfit_task_load;
9974 *sg_status |= SG_OVERLOAD;
9975 }
9976 } else if ((env->idle != CPU_NOT_IDLE) &&
9977 sched_reduced_capacity(rq, env->sd)) {
9978 /* Check for a task running on a CPU with reduced capacity */
9979 if (sgs->group_misfit_task_load < load)
9980 sgs->group_misfit_task_load = load;
9981 }
9982 }
9983
9984 sgs->group_capacity = group->sgc->capacity;
9985
9986 sgs->group_weight = group->group_weight;
9987
9988 /* Check if dst CPU is idle and preferred to this group */
9989 if (!local_group && env->sd->flags & SD_ASYM_PACKING &&
9990 env->idle != CPU_NOT_IDLE && sgs->sum_h_nr_running &&
9991 sched_asym(env, sds, sgs, group)) {
9992 sgs->group_asym_packing = 1;
9993 }
9994
9995 /* Check for loaded SMT group to be balanced to dst CPU */
9996 if (!local_group && smt_balance(env, sgs, group))
9997 sgs->group_smt_balance = 1;
9998
9999 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
10000
10001 /* Computing avg_load makes sense only when group is overloaded */
10002 if (sgs->group_type == group_overloaded)
10003 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10004 sgs->group_capacity;
10005 }
10006
10007 /**
10008 * update_sd_pick_busiest - return 1 on busiest group
10009 * @env: The load balancing environment.
10010 * @sds: sched_domain statistics
10011 * @sg: sched_group candidate to be checked for being the busiest
10012 * @sgs: sched_group statistics
10013 *
10014 * Determine if @sg is a busier group than the previously selected
10015 * busiest group.
10016 *
10017 * Return: %true if @sg is a busier group than the previously selected
10018 * busiest group. %false otherwise.
10019 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)10020 static bool update_sd_pick_busiest(struct lb_env *env,
10021 struct sd_lb_stats *sds,
10022 struct sched_group *sg,
10023 struct sg_lb_stats *sgs)
10024 {
10025 struct sg_lb_stats *busiest = &sds->busiest_stat;
10026
10027 /* Make sure that there is at least one task to pull */
10028 if (!sgs->sum_h_nr_running)
10029 return false;
10030
10031 /*
10032 * Don't try to pull misfit tasks we can't help.
10033 * We can use max_capacity here as reduction in capacity on some
10034 * CPUs in the group should either be possible to resolve
10035 * internally or be covered by avg_load imbalance (eventually).
10036 */
10037 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10038 (sgs->group_type == group_misfit_task) &&
10039 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) ||
10040 sds->local_stat.group_type != group_has_spare))
10041 return false;
10042
10043 if (sgs->group_type > busiest->group_type)
10044 return true;
10045
10046 if (sgs->group_type < busiest->group_type)
10047 return false;
10048
10049 /*
10050 * The candidate and the current busiest group are the same type of
10051 * group. Let check which one is the busiest according to the type.
10052 */
10053
10054 switch (sgs->group_type) {
10055 case group_overloaded:
10056 /* Select the overloaded group with highest avg_load. */
10057 if (sgs->avg_load <= busiest->avg_load)
10058 return false;
10059 break;
10060
10061 case group_imbalanced:
10062 /*
10063 * Select the 1st imbalanced group as we don't have any way to
10064 * choose one more than another.
10065 */
10066 return false;
10067
10068 case group_asym_packing:
10069 /* Prefer to move from lowest priority CPU's work */
10070 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
10071 return false;
10072 break;
10073
10074 case group_misfit_task:
10075 /*
10076 * If we have more than one misfit sg go with the biggest
10077 * misfit.
10078 */
10079 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
10080 return false;
10081 break;
10082
10083 case group_smt_balance:
10084 /*
10085 * Check if we have spare CPUs on either SMT group to
10086 * choose has spare or fully busy handling.
10087 */
10088 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0)
10089 goto has_spare;
10090
10091 fallthrough;
10092
10093 case group_fully_busy:
10094 /*
10095 * Select the fully busy group with highest avg_load. In
10096 * theory, there is no need to pull task from such kind of
10097 * group because tasks have all compute capacity that they need
10098 * but we can still improve the overall throughput by reducing
10099 * contention when accessing shared HW resources.
10100 *
10101 * XXX for now avg_load is not computed and always 0 so we
10102 * select the 1st one, except if @sg is composed of SMT
10103 * siblings.
10104 */
10105
10106 if (sgs->avg_load < busiest->avg_load)
10107 return false;
10108
10109 if (sgs->avg_load == busiest->avg_load) {
10110 /*
10111 * SMT sched groups need more help than non-SMT groups.
10112 * If @sg happens to also be SMT, either choice is good.
10113 */
10114 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY)
10115 return false;
10116 }
10117
10118 break;
10119
10120 case group_has_spare:
10121 /*
10122 * Do not pick sg with SMT CPUs over sg with pure CPUs,
10123 * as we do not want to pull task off SMT core with one task
10124 * and make the core idle.
10125 */
10126 if (smt_vs_nonsmt_groups(sds->busiest, sg)) {
10127 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1)
10128 return false;
10129 else
10130 return true;
10131 }
10132 has_spare:
10133
10134 /*
10135 * Select not overloaded group with lowest number of idle cpus
10136 * and highest number of running tasks. We could also compare
10137 * the spare capacity which is more stable but it can end up
10138 * that the group has less spare capacity but finally more idle
10139 * CPUs which means less opportunity to pull tasks.
10140 */
10141 if (sgs->idle_cpus > busiest->idle_cpus)
10142 return false;
10143 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
10144 (sgs->sum_nr_running <= busiest->sum_nr_running))
10145 return false;
10146
10147 break;
10148 }
10149
10150 /*
10151 * Candidate sg has no more than one task per CPU and has higher
10152 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
10153 * throughput. Maximize throughput, power/energy consequences are not
10154 * considered.
10155 */
10156 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
10157 (sgs->group_type <= group_fully_busy) &&
10158 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu))))
10159 return false;
10160
10161 return true;
10162 }
10163
10164 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)10165 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10166 {
10167 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
10168 return regular;
10169 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
10170 return remote;
10171 return all;
10172 }
10173
fbq_classify_rq(struct rq * rq)10174 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10175 {
10176 if (rq->nr_running > rq->nr_numa_running)
10177 return regular;
10178 if (rq->nr_running > rq->nr_preferred_running)
10179 return remote;
10180 return all;
10181 }
10182 #else
fbq_classify_group(struct sg_lb_stats * sgs)10183 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
10184 {
10185 return all;
10186 }
10187
fbq_classify_rq(struct rq * rq)10188 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
10189 {
10190 return regular;
10191 }
10192 #endif /* CONFIG_NUMA_BALANCING */
10193
10194
10195 struct sg_lb_stats;
10196
10197 /*
10198 * task_running_on_cpu - return 1 if @p is running on @cpu.
10199 */
10200
task_running_on_cpu(int cpu,struct task_struct * p)10201 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
10202 {
10203 /* Task has no contribution or is new */
10204 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
10205 return 0;
10206
10207 if (task_on_rq_queued(p))
10208 return 1;
10209
10210 return 0;
10211 }
10212
10213 /**
10214 * idle_cpu_without - would a given CPU be idle without p ?
10215 * @cpu: the processor on which idleness is tested.
10216 * @p: task which should be ignored.
10217 *
10218 * Return: 1 if the CPU would be idle. 0 otherwise.
10219 */
idle_cpu_without(int cpu,struct task_struct * p)10220 static int idle_cpu_without(int cpu, struct task_struct *p)
10221 {
10222 struct rq *rq = cpu_rq(cpu);
10223
10224 if (rq->curr != rq->idle && rq->curr != p)
10225 return 0;
10226
10227 /*
10228 * rq->nr_running can't be used but an updated version without the
10229 * impact of p on cpu must be used instead. The updated nr_running
10230 * be computed and tested before calling idle_cpu_without().
10231 */
10232
10233 #ifdef CONFIG_SMP
10234 if (rq->ttwu_pending)
10235 return 0;
10236 #endif
10237
10238 return 1;
10239 }
10240
10241 /*
10242 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
10243 * @sd: The sched_domain level to look for idlest group.
10244 * @group: sched_group whose statistics are to be updated.
10245 * @sgs: variable to hold the statistics for this group.
10246 * @p: The task for which we look for the idlest group/CPU.
10247 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)10248 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
10249 struct sched_group *group,
10250 struct sg_lb_stats *sgs,
10251 struct task_struct *p)
10252 {
10253 int i, nr_running;
10254
10255 memset(sgs, 0, sizeof(*sgs));
10256
10257 /* Assume that task can't fit any CPU of the group */
10258 if (sd->flags & SD_ASYM_CPUCAPACITY)
10259 sgs->group_misfit_task_load = 1;
10260
10261 for_each_cpu(i, sched_group_span(group)) {
10262 struct rq *rq = cpu_rq(i);
10263 unsigned int local;
10264
10265 sgs->group_load += cpu_load_without(rq, p);
10266 sgs->group_util += cpu_util_without(i, p);
10267 sgs->group_runnable += cpu_runnable_without(rq, p);
10268 local = task_running_on_cpu(i, p);
10269 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
10270
10271 nr_running = rq->nr_running - local;
10272 sgs->sum_nr_running += nr_running;
10273
10274 /*
10275 * No need to call idle_cpu_without() if nr_running is not 0
10276 */
10277 if (!nr_running && idle_cpu_without(i, p))
10278 sgs->idle_cpus++;
10279
10280 /* Check if task fits in the CPU */
10281 if (sd->flags & SD_ASYM_CPUCAPACITY &&
10282 sgs->group_misfit_task_load &&
10283 task_fits_cpu(p, i))
10284 sgs->group_misfit_task_load = 0;
10285
10286 }
10287
10288 sgs->group_capacity = group->sgc->capacity;
10289
10290 sgs->group_weight = group->group_weight;
10291
10292 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
10293
10294 /*
10295 * Computing avg_load makes sense only when group is fully busy or
10296 * overloaded
10297 */
10298 if (sgs->group_type == group_fully_busy ||
10299 sgs->group_type == group_overloaded)
10300 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
10301 sgs->group_capacity;
10302 }
10303
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)10304 static bool update_pick_idlest(struct sched_group *idlest,
10305 struct sg_lb_stats *idlest_sgs,
10306 struct sched_group *group,
10307 struct sg_lb_stats *sgs)
10308 {
10309 if (sgs->group_type < idlest_sgs->group_type)
10310 return true;
10311
10312 if (sgs->group_type > idlest_sgs->group_type)
10313 return false;
10314
10315 /*
10316 * The candidate and the current idlest group are the same type of
10317 * group. Let check which one is the idlest according to the type.
10318 */
10319
10320 switch (sgs->group_type) {
10321 case group_overloaded:
10322 case group_fully_busy:
10323 /* Select the group with lowest avg_load. */
10324 if (idlest_sgs->avg_load <= sgs->avg_load)
10325 return false;
10326 break;
10327
10328 case group_imbalanced:
10329 case group_asym_packing:
10330 case group_smt_balance:
10331 /* Those types are not used in the slow wakeup path */
10332 return false;
10333
10334 case group_misfit_task:
10335 /* Select group with the highest max capacity */
10336 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
10337 return false;
10338 break;
10339
10340 case group_has_spare:
10341 /* Select group with most idle CPUs */
10342 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
10343 return false;
10344
10345 /* Select group with lowest group_util */
10346 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
10347 idlest_sgs->group_util <= sgs->group_util)
10348 return false;
10349
10350 break;
10351 }
10352
10353 return true;
10354 }
10355
10356 /*
10357 * find_idlest_group() finds and returns the least busy CPU group within the
10358 * domain.
10359 *
10360 * Assumes p is allowed on at least one CPU in sd.
10361 */
10362 static struct sched_group *
find_idlest_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)10363 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
10364 {
10365 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
10366 struct sg_lb_stats local_sgs, tmp_sgs;
10367 struct sg_lb_stats *sgs;
10368 unsigned long imbalance;
10369 struct sg_lb_stats idlest_sgs = {
10370 .avg_load = UINT_MAX,
10371 .group_type = group_overloaded,
10372 };
10373
10374 do {
10375 int local_group;
10376
10377 /* Skip over this group if it has no CPUs allowed */
10378 if (!cpumask_intersects(sched_group_span(group),
10379 p->cpus_ptr))
10380 continue;
10381
10382 /* Skip over this group if no cookie matched */
10383 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group))
10384 continue;
10385
10386 local_group = cpumask_test_cpu(this_cpu,
10387 sched_group_span(group));
10388
10389 if (local_group) {
10390 sgs = &local_sgs;
10391 local = group;
10392 } else {
10393 sgs = &tmp_sgs;
10394 }
10395
10396 update_sg_wakeup_stats(sd, group, sgs, p);
10397
10398 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
10399 idlest = group;
10400 idlest_sgs = *sgs;
10401 }
10402
10403 } while (group = group->next, group != sd->groups);
10404
10405
10406 /* There is no idlest group to push tasks to */
10407 if (!idlest)
10408 return NULL;
10409
10410 /* The local group has been skipped because of CPU affinity */
10411 if (!local)
10412 return idlest;
10413
10414 /*
10415 * If the local group is idler than the selected idlest group
10416 * don't try and push the task.
10417 */
10418 if (local_sgs.group_type < idlest_sgs.group_type)
10419 return NULL;
10420
10421 /*
10422 * If the local group is busier than the selected idlest group
10423 * try and push the task.
10424 */
10425 if (local_sgs.group_type > idlest_sgs.group_type)
10426 return idlest;
10427
10428 switch (local_sgs.group_type) {
10429 case group_overloaded:
10430 case group_fully_busy:
10431
10432 /* Calculate allowed imbalance based on load */
10433 imbalance = scale_load_down(NICE_0_LOAD) *
10434 (sd->imbalance_pct-100) / 100;
10435
10436 /*
10437 * When comparing groups across NUMA domains, it's possible for
10438 * the local domain to be very lightly loaded relative to the
10439 * remote domains but "imbalance" skews the comparison making
10440 * remote CPUs look much more favourable. When considering
10441 * cross-domain, add imbalance to the load on the remote node
10442 * and consider staying local.
10443 */
10444
10445 if ((sd->flags & SD_NUMA) &&
10446 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
10447 return NULL;
10448
10449 /*
10450 * If the local group is less loaded than the selected
10451 * idlest group don't try and push any tasks.
10452 */
10453 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
10454 return NULL;
10455
10456 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
10457 return NULL;
10458 break;
10459
10460 case group_imbalanced:
10461 case group_asym_packing:
10462 case group_smt_balance:
10463 /* Those type are not used in the slow wakeup path */
10464 return NULL;
10465
10466 case group_misfit_task:
10467 /* Select group with the highest max capacity */
10468 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
10469 return NULL;
10470 break;
10471
10472 case group_has_spare:
10473 #ifdef CONFIG_NUMA
10474 if (sd->flags & SD_NUMA) {
10475 int imb_numa_nr = sd->imb_numa_nr;
10476 #ifdef CONFIG_NUMA_BALANCING
10477 int idlest_cpu;
10478 /*
10479 * If there is spare capacity at NUMA, try to select
10480 * the preferred node
10481 */
10482 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
10483 return NULL;
10484
10485 idlest_cpu = cpumask_first(sched_group_span(idlest));
10486 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
10487 return idlest;
10488 #endif /* CONFIG_NUMA_BALANCING */
10489 /*
10490 * Otherwise, keep the task close to the wakeup source
10491 * and improve locality if the number of running tasks
10492 * would remain below threshold where an imbalance is
10493 * allowed while accounting for the possibility the
10494 * task is pinned to a subset of CPUs. If there is a
10495 * real need of migration, periodic load balance will
10496 * take care of it.
10497 */
10498 if (p->nr_cpus_allowed != NR_CPUS) {
10499 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask);
10500
10501 cpumask_and(cpus, sched_group_span(local), p->cpus_ptr);
10502 imb_numa_nr = min(cpumask_weight(cpus), sd->imb_numa_nr);
10503 }
10504
10505 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus);
10506 if (!adjust_numa_imbalance(imbalance,
10507 local_sgs.sum_nr_running + 1,
10508 imb_numa_nr)) {
10509 return NULL;
10510 }
10511 }
10512 #endif /* CONFIG_NUMA */
10513
10514 /*
10515 * Select group with highest number of idle CPUs. We could also
10516 * compare the utilization which is more stable but it can end
10517 * up that the group has less spare capacity but finally more
10518 * idle CPUs which means more opportunity to run task.
10519 */
10520 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
10521 return NULL;
10522 break;
10523 }
10524
10525 return idlest;
10526 }
10527
update_idle_cpu_scan(struct lb_env * env,unsigned long sum_util)10528 static void update_idle_cpu_scan(struct lb_env *env,
10529 unsigned long sum_util)
10530 {
10531 struct sched_domain_shared *sd_share;
10532 int llc_weight, pct;
10533 u64 x, y, tmp;
10534 /*
10535 * Update the number of CPUs to scan in LLC domain, which could
10536 * be used as a hint in select_idle_cpu(). The update of sd_share
10537 * could be expensive because it is within a shared cache line.
10538 * So the write of this hint only occurs during periodic load
10539 * balancing, rather than CPU_NEWLY_IDLE, because the latter
10540 * can fire way more frequently than the former.
10541 */
10542 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE)
10543 return;
10544
10545 llc_weight = per_cpu(sd_llc_size, env->dst_cpu);
10546 if (env->sd->span_weight != llc_weight)
10547 return;
10548
10549 sd_share = rcu_dereference(per_cpu(sd_llc_shared, env->dst_cpu));
10550 if (!sd_share)
10551 return;
10552
10553 /*
10554 * The number of CPUs to search drops as sum_util increases, when
10555 * sum_util hits 85% or above, the scan stops.
10556 * The reason to choose 85% as the threshold is because this is the
10557 * imbalance_pct(117) when a LLC sched group is overloaded.
10558 *
10559 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1]
10560 * and y'= y / SCHED_CAPACITY_SCALE
10561 *
10562 * x is the ratio of sum_util compared to the CPU capacity:
10563 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE)
10564 * y' is the ratio of CPUs to be scanned in the LLC domain,
10565 * and the number of CPUs to scan is calculated by:
10566 *
10567 * nr_scan = llc_weight * y' [2]
10568 *
10569 * When x hits the threshold of overloaded, AKA, when
10570 * x = 100 / pct, y drops to 0. According to [1],
10571 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000
10572 *
10573 * Scale x by SCHED_CAPACITY_SCALE:
10574 * x' = sum_util / llc_weight; [3]
10575 *
10576 * and finally [1] becomes:
10577 * y = SCHED_CAPACITY_SCALE -
10578 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4]
10579 *
10580 */
10581 /* equation [3] */
10582 x = sum_util;
10583 do_div(x, llc_weight);
10584
10585 /* equation [4] */
10586 pct = env->sd->imbalance_pct;
10587 tmp = x * x * pct * pct;
10588 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE);
10589 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE);
10590 y = SCHED_CAPACITY_SCALE - tmp;
10591
10592 /* equation [2] */
10593 y *= llc_weight;
10594 do_div(y, SCHED_CAPACITY_SCALE);
10595 if ((int)y != sd_share->nr_idle_scan)
10596 WRITE_ONCE(sd_share->nr_idle_scan, (int)y);
10597 }
10598
10599 /**
10600 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
10601 * @env: The load balancing environment.
10602 * @sds: variable to hold the statistics for this sched_domain.
10603 */
10604
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)10605 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
10606 {
10607 struct sched_group *sg = env->sd->groups;
10608 struct sg_lb_stats *local = &sds->local_stat;
10609 struct sg_lb_stats tmp_sgs;
10610 unsigned long sum_util = 0;
10611 int sg_status = 0;
10612
10613 do {
10614 struct sg_lb_stats *sgs = &tmp_sgs;
10615 int local_group;
10616
10617 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
10618 if (local_group) {
10619 sds->local = sg;
10620 sgs = local;
10621
10622 if (env->idle != CPU_NEWLY_IDLE ||
10623 time_after_eq(jiffies, sg->sgc->next_update))
10624 update_group_capacity(env->sd, env->dst_cpu);
10625 }
10626
10627 update_sg_lb_stats(env, sds, sg, sgs, &sg_status);
10628
10629 if (local_group)
10630 goto next_group;
10631
10632
10633 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
10634 sds->busiest = sg;
10635 sds->busiest_stat = *sgs;
10636 }
10637
10638 next_group:
10639 /* Now, start updating sd_lb_stats */
10640 sds->total_load += sgs->group_load;
10641 sds->total_capacity += sgs->group_capacity;
10642
10643 sum_util += sgs->group_util;
10644 sg = sg->next;
10645 } while (sg != env->sd->groups);
10646
10647 /*
10648 * Indicate that the child domain of the busiest group prefers tasks
10649 * go to a child's sibling domains first. NB the flags of a sched group
10650 * are those of the child domain.
10651 */
10652 if (sds->busiest)
10653 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING);
10654
10655
10656 if (env->sd->flags & SD_NUMA)
10657 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
10658
10659 if (!env->sd->parent) {
10660 struct root_domain *rd = env->dst_rq->rd;
10661
10662 /* update overload indicator if we are at root domain */
10663 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
10664
10665 /* Update over-utilization (tipping point, U >= 0) indicator */
10666 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
10667 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
10668 } else if (sg_status & SG_OVERUTILIZED) {
10669 struct root_domain *rd = env->dst_rq->rd;
10670
10671 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
10672 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
10673 }
10674
10675 update_idle_cpu_scan(env, sum_util);
10676 }
10677
10678 /**
10679 * calculate_imbalance - Calculate the amount of imbalance present within the
10680 * groups of a given sched_domain during load balance.
10681 * @env: load balance environment
10682 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
10683 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)10684 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
10685 {
10686 struct sg_lb_stats *local, *busiest;
10687
10688 local = &sds->local_stat;
10689 busiest = &sds->busiest_stat;
10690
10691 if (busiest->group_type == group_misfit_task) {
10692 if (env->sd->flags & SD_ASYM_CPUCAPACITY) {
10693 /* Set imbalance to allow misfit tasks to be balanced. */
10694 env->migration_type = migrate_misfit;
10695 env->imbalance = 1;
10696 } else {
10697 /*
10698 * Set load imbalance to allow moving task from cpu
10699 * with reduced capacity.
10700 */
10701 env->migration_type = migrate_load;
10702 env->imbalance = busiest->group_misfit_task_load;
10703 }
10704 return;
10705 }
10706
10707 if (busiest->group_type == group_asym_packing) {
10708 /*
10709 * In case of asym capacity, we will try to migrate all load to
10710 * the preferred CPU.
10711 */
10712 env->migration_type = migrate_task;
10713 env->imbalance = busiest->sum_h_nr_running;
10714 return;
10715 }
10716
10717 if (busiest->group_type == group_smt_balance) {
10718 /* Reduce number of tasks sharing CPU capacity */
10719 env->migration_type = migrate_task;
10720 env->imbalance = 1;
10721 return;
10722 }
10723
10724 if (busiest->group_type == group_imbalanced) {
10725 /*
10726 * In the group_imb case we cannot rely on group-wide averages
10727 * to ensure CPU-load equilibrium, try to move any task to fix
10728 * the imbalance. The next load balance will take care of
10729 * balancing back the system.
10730 */
10731 env->migration_type = migrate_task;
10732 env->imbalance = 1;
10733 return;
10734 }
10735
10736 /*
10737 * Try to use spare capacity of local group without overloading it or
10738 * emptying busiest.
10739 */
10740 if (local->group_type == group_has_spare) {
10741 if ((busiest->group_type > group_fully_busy) &&
10742 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
10743 /*
10744 * If busiest is overloaded, try to fill spare
10745 * capacity. This might end up creating spare capacity
10746 * in busiest or busiest still being overloaded but
10747 * there is no simple way to directly compute the
10748 * amount of load to migrate in order to balance the
10749 * system.
10750 */
10751 env->migration_type = migrate_util;
10752 env->imbalance = max(local->group_capacity, local->group_util) -
10753 local->group_util;
10754
10755 /*
10756 * In some cases, the group's utilization is max or even
10757 * higher than capacity because of migrations but the
10758 * local CPU is (newly) idle. There is at least one
10759 * waiting task in this overloaded busiest group. Let's
10760 * try to pull it.
10761 */
10762 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
10763 env->migration_type = migrate_task;
10764 env->imbalance = 1;
10765 }
10766
10767 return;
10768 }
10769
10770 if (busiest->group_weight == 1 || sds->prefer_sibling) {
10771 /*
10772 * When prefer sibling, evenly spread running tasks on
10773 * groups.
10774 */
10775 env->migration_type = migrate_task;
10776 env->imbalance = sibling_imbalance(env, sds, busiest, local);
10777 } else {
10778
10779 /*
10780 * If there is no overload, we just want to even the number of
10781 * idle cpus.
10782 */
10783 env->migration_type = migrate_task;
10784 env->imbalance = max_t(long, 0,
10785 (local->idle_cpus - busiest->idle_cpus));
10786 }
10787
10788 #ifdef CONFIG_NUMA
10789 /* Consider allowing a small imbalance between NUMA groups */
10790 if (env->sd->flags & SD_NUMA) {
10791 env->imbalance = adjust_numa_imbalance(env->imbalance,
10792 local->sum_nr_running + 1,
10793 env->sd->imb_numa_nr);
10794 }
10795 #endif
10796
10797 /* Number of tasks to move to restore balance */
10798 env->imbalance >>= 1;
10799
10800 return;
10801 }
10802
10803 /*
10804 * Local is fully busy but has to take more load to relieve the
10805 * busiest group
10806 */
10807 if (local->group_type < group_overloaded) {
10808 /*
10809 * Local will become overloaded so the avg_load metrics are
10810 * finally needed.
10811 */
10812
10813 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
10814 local->group_capacity;
10815
10816 /*
10817 * If the local group is more loaded than the selected
10818 * busiest group don't try to pull any tasks.
10819 */
10820 if (local->avg_load >= busiest->avg_load) {
10821 env->imbalance = 0;
10822 return;
10823 }
10824
10825 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
10826 sds->total_capacity;
10827
10828 /*
10829 * If the local group is more loaded than the average system
10830 * load, don't try to pull any tasks.
10831 */
10832 if (local->avg_load >= sds->avg_load) {
10833 env->imbalance = 0;
10834 return;
10835 }
10836
10837 }
10838
10839 /*
10840 * Both group are or will become overloaded and we're trying to get all
10841 * the CPUs to the average_load, so we don't want to push ourselves
10842 * above the average load, nor do we wish to reduce the max loaded CPU
10843 * below the average load. At the same time, we also don't want to
10844 * reduce the group load below the group capacity. Thus we look for
10845 * the minimum possible imbalance.
10846 */
10847 env->migration_type = migrate_load;
10848 env->imbalance = min(
10849 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
10850 (sds->avg_load - local->avg_load) * local->group_capacity
10851 ) / SCHED_CAPACITY_SCALE;
10852 }
10853
10854 /******* find_busiest_group() helpers end here *********************/
10855
10856 /*
10857 * Decision matrix according to the local and busiest group type:
10858 *
10859 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
10860 * has_spare nr_idle balanced N/A N/A balanced balanced
10861 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
10862 * misfit_task force N/A N/A N/A N/A N/A
10863 * asym_packing force force N/A N/A force force
10864 * imbalanced force force N/A N/A force force
10865 * overloaded force force N/A N/A force avg_load
10866 *
10867 * N/A : Not Applicable because already filtered while updating
10868 * statistics.
10869 * balanced : The system is balanced for these 2 groups.
10870 * force : Calculate the imbalance as load migration is probably needed.
10871 * avg_load : Only if imbalance is significant enough.
10872 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
10873 * different in groups.
10874 */
10875
10876 /**
10877 * find_busiest_group - Returns the busiest group within the sched_domain
10878 * if there is an imbalance.
10879 * @env: The load balancing environment.
10880 *
10881 * Also calculates the amount of runnable load which should be moved
10882 * to restore balance.
10883 *
10884 * Return: - The busiest group if imbalance exists.
10885 */
find_busiest_group(struct lb_env * env)10886 static struct sched_group *find_busiest_group(struct lb_env *env)
10887 {
10888 struct sg_lb_stats *local, *busiest;
10889 struct sd_lb_stats sds;
10890
10891 init_sd_lb_stats(&sds);
10892
10893 /*
10894 * Compute the various statistics relevant for load balancing at
10895 * this level.
10896 */
10897 update_sd_lb_stats(env, &sds);
10898
10899 /* There is no busy sibling group to pull tasks from */
10900 if (!sds.busiest)
10901 goto out_balanced;
10902
10903 busiest = &sds.busiest_stat;
10904
10905 /* Misfit tasks should be dealt with regardless of the avg load */
10906 if (busiest->group_type == group_misfit_task)
10907 goto force_balance;
10908
10909 if (sched_energy_enabled()) {
10910 struct root_domain *rd = env->dst_rq->rd;
10911
10912 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
10913 goto out_balanced;
10914 }
10915
10916 /* ASYM feature bypasses nice load balance check */
10917 if (busiest->group_type == group_asym_packing)
10918 goto force_balance;
10919
10920 /*
10921 * If the busiest group is imbalanced the below checks don't
10922 * work because they assume all things are equal, which typically
10923 * isn't true due to cpus_ptr constraints and the like.
10924 */
10925 if (busiest->group_type == group_imbalanced)
10926 goto force_balance;
10927
10928 local = &sds.local_stat;
10929 /*
10930 * If the local group is busier than the selected busiest group
10931 * don't try and pull any tasks.
10932 */
10933 if (local->group_type > busiest->group_type)
10934 goto out_balanced;
10935
10936 /*
10937 * When groups are overloaded, use the avg_load to ensure fairness
10938 * between tasks.
10939 */
10940 if (local->group_type == group_overloaded) {
10941 /*
10942 * If the local group is more loaded than the selected
10943 * busiest group don't try to pull any tasks.
10944 */
10945 if (local->avg_load >= busiest->avg_load)
10946 goto out_balanced;
10947
10948 /* XXX broken for overlapping NUMA groups */
10949 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
10950 sds.total_capacity;
10951
10952 /*
10953 * Don't pull any tasks if this group is already above the
10954 * domain average load.
10955 */
10956 if (local->avg_load >= sds.avg_load)
10957 goto out_balanced;
10958
10959 /*
10960 * If the busiest group is more loaded, use imbalance_pct to be
10961 * conservative.
10962 */
10963 if (100 * busiest->avg_load <=
10964 env->sd->imbalance_pct * local->avg_load)
10965 goto out_balanced;
10966 }
10967
10968 /*
10969 * Try to move all excess tasks to a sibling domain of the busiest
10970 * group's child domain.
10971 */
10972 if (sds.prefer_sibling && local->group_type == group_has_spare &&
10973 sibling_imbalance(env, &sds, busiest, local) > 1)
10974 goto force_balance;
10975
10976 if (busiest->group_type != group_overloaded) {
10977 if (env->idle == CPU_NOT_IDLE) {
10978 /*
10979 * If the busiest group is not overloaded (and as a
10980 * result the local one too) but this CPU is already
10981 * busy, let another idle CPU try to pull task.
10982 */
10983 goto out_balanced;
10984 }
10985
10986 if (busiest->group_type == group_smt_balance &&
10987 smt_vs_nonsmt_groups(sds.local, sds.busiest)) {
10988 /* Let non SMT CPU pull from SMT CPU sharing with sibling */
10989 goto force_balance;
10990 }
10991
10992 if (busiest->group_weight > 1 &&
10993 local->idle_cpus <= (busiest->idle_cpus + 1)) {
10994 /*
10995 * If the busiest group is not overloaded
10996 * and there is no imbalance between this and busiest
10997 * group wrt idle CPUs, it is balanced. The imbalance
10998 * becomes significant if the diff is greater than 1
10999 * otherwise we might end up to just move the imbalance
11000 * on another group. Of course this applies only if
11001 * there is more than 1 CPU per group.
11002 */
11003 goto out_balanced;
11004 }
11005
11006 if (busiest->sum_h_nr_running == 1) {
11007 /*
11008 * busiest doesn't have any tasks waiting to run
11009 */
11010 goto out_balanced;
11011 }
11012 }
11013
11014 force_balance:
11015 /* Looks like there is an imbalance. Compute it */
11016 calculate_imbalance(env, &sds);
11017 return env->imbalance ? sds.busiest : NULL;
11018
11019 out_balanced:
11020 env->imbalance = 0;
11021 return NULL;
11022 }
11023
11024 /*
11025 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
11026 */
find_busiest_queue(struct lb_env * env,struct sched_group * group)11027 static struct rq *find_busiest_queue(struct lb_env *env,
11028 struct sched_group *group)
11029 {
11030 struct rq *busiest = NULL, *rq;
11031 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
11032 unsigned int busiest_nr = 0;
11033 int i;
11034
11035 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
11036 unsigned long capacity, load, util;
11037 unsigned int nr_running;
11038 enum fbq_type rt;
11039
11040 rq = cpu_rq(i);
11041 rt = fbq_classify_rq(rq);
11042
11043 /*
11044 * We classify groups/runqueues into three groups:
11045 * - regular: there are !numa tasks
11046 * - remote: there are numa tasks that run on the 'wrong' node
11047 * - all: there is no distinction
11048 *
11049 * In order to avoid migrating ideally placed numa tasks,
11050 * ignore those when there's better options.
11051 *
11052 * If we ignore the actual busiest queue to migrate another
11053 * task, the next balance pass can still reduce the busiest
11054 * queue by moving tasks around inside the node.
11055 *
11056 * If we cannot move enough load due to this classification
11057 * the next pass will adjust the group classification and
11058 * allow migration of more tasks.
11059 *
11060 * Both cases only affect the total convergence complexity.
11061 */
11062 if (rt > env->fbq_type)
11063 continue;
11064
11065 nr_running = rq->cfs.h_nr_running;
11066 if (!nr_running)
11067 continue;
11068
11069 capacity = capacity_of(i);
11070
11071 /*
11072 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
11073 * eventually lead to active_balancing high->low capacity.
11074 * Higher per-CPU capacity is considered better than balancing
11075 * average load.
11076 */
11077 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
11078 !capacity_greater(capacity_of(env->dst_cpu), capacity) &&
11079 nr_running == 1)
11080 continue;
11081
11082 /*
11083 * Make sure we only pull tasks from a CPU of lower priority
11084 * when balancing between SMT siblings.
11085 *
11086 * If balancing between cores, let lower priority CPUs help
11087 * SMT cores with more than one busy sibling.
11088 */
11089 if ((env->sd->flags & SD_ASYM_PACKING) &&
11090 sched_use_asym_prio(env->sd, i) &&
11091 sched_asym_prefer(i, env->dst_cpu) &&
11092 nr_running == 1)
11093 continue;
11094
11095 switch (env->migration_type) {
11096 case migrate_load:
11097 /*
11098 * When comparing with load imbalance, use cpu_load()
11099 * which is not scaled with the CPU capacity.
11100 */
11101 load = cpu_load(rq);
11102
11103 if (nr_running == 1 && load > env->imbalance &&
11104 !check_cpu_capacity(rq, env->sd))
11105 break;
11106
11107 /*
11108 * For the load comparisons with the other CPUs,
11109 * consider the cpu_load() scaled with the CPU
11110 * capacity, so that the load can be moved away
11111 * from the CPU that is potentially running at a
11112 * lower capacity.
11113 *
11114 * Thus we're looking for max(load_i / capacity_i),
11115 * crosswise multiplication to rid ourselves of the
11116 * division works out to:
11117 * load_i * capacity_j > load_j * capacity_i;
11118 * where j is our previous maximum.
11119 */
11120 if (load * busiest_capacity > busiest_load * capacity) {
11121 busiest_load = load;
11122 busiest_capacity = capacity;
11123 busiest = rq;
11124 }
11125 break;
11126
11127 case migrate_util:
11128 util = cpu_util_cfs_boost(i);
11129
11130 /*
11131 * Don't try to pull utilization from a CPU with one
11132 * running task. Whatever its utilization, we will fail
11133 * detach the task.
11134 */
11135 if (nr_running <= 1)
11136 continue;
11137
11138 if (busiest_util < util) {
11139 busiest_util = util;
11140 busiest = rq;
11141 }
11142 break;
11143
11144 case migrate_task:
11145 if (busiest_nr < nr_running) {
11146 busiest_nr = nr_running;
11147 busiest = rq;
11148 }
11149 break;
11150
11151 case migrate_misfit:
11152 /*
11153 * For ASYM_CPUCAPACITY domains with misfit tasks we
11154 * simply seek the "biggest" misfit task.
11155 */
11156 if (rq->misfit_task_load > busiest_load) {
11157 busiest_load = rq->misfit_task_load;
11158 busiest = rq;
11159 }
11160
11161 break;
11162
11163 }
11164 }
11165
11166 return busiest;
11167 }
11168
11169 /*
11170 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
11171 * so long as it is large enough.
11172 */
11173 #define MAX_PINNED_INTERVAL 512
11174
11175 static inline bool
asym_active_balance(struct lb_env * env)11176 asym_active_balance(struct lb_env *env)
11177 {
11178 /*
11179 * ASYM_PACKING needs to force migrate tasks from busy but lower
11180 * priority CPUs in order to pack all tasks in the highest priority
11181 * CPUs. When done between cores, do it only if the whole core if the
11182 * whole core is idle.
11183 *
11184 * If @env::src_cpu is an SMT core with busy siblings, let
11185 * the lower priority @env::dst_cpu help it. Do not follow
11186 * CPU priority.
11187 */
11188 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
11189 sched_use_asym_prio(env->sd, env->dst_cpu) &&
11190 (sched_asym_prefer(env->dst_cpu, env->src_cpu) ||
11191 !sched_use_asym_prio(env->sd, env->src_cpu));
11192 }
11193
11194 static inline bool
imbalanced_active_balance(struct lb_env * env)11195 imbalanced_active_balance(struct lb_env *env)
11196 {
11197 struct sched_domain *sd = env->sd;
11198
11199 /*
11200 * The imbalanced case includes the case of pinned tasks preventing a fair
11201 * distribution of the load on the system but also the even distribution of the
11202 * threads on a system with spare capacity
11203 */
11204 if ((env->migration_type == migrate_task) &&
11205 (sd->nr_balance_failed > sd->cache_nice_tries+2))
11206 return 1;
11207
11208 return 0;
11209 }
11210
need_active_balance(struct lb_env * env)11211 static int need_active_balance(struct lb_env *env)
11212 {
11213 struct sched_domain *sd = env->sd;
11214
11215 if (asym_active_balance(env))
11216 return 1;
11217
11218 if (imbalanced_active_balance(env))
11219 return 1;
11220
11221 /*
11222 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
11223 * It's worth migrating the task if the src_cpu's capacity is reduced
11224 * because of other sched_class or IRQs if more capacity stays
11225 * available on dst_cpu.
11226 */
11227 if ((env->idle != CPU_NOT_IDLE) &&
11228 (env->src_rq->cfs.h_nr_running == 1)) {
11229 if ((check_cpu_capacity(env->src_rq, sd)) &&
11230 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
11231 return 1;
11232 }
11233
11234 if (env->migration_type == migrate_misfit)
11235 return 1;
11236
11237 return 0;
11238 }
11239
11240 static int active_load_balance_cpu_stop(void *data);
11241
should_we_balance(struct lb_env * env)11242 static int should_we_balance(struct lb_env *env)
11243 {
11244 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask);
11245 struct sched_group *sg = env->sd->groups;
11246 int cpu, idle_smt = -1;
11247
11248 /*
11249 * Ensure the balancing environment is consistent; can happen
11250 * when the softirq triggers 'during' hotplug.
11251 */
11252 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
11253 return 0;
11254
11255 /*
11256 * In the newly idle case, we will allow all the CPUs
11257 * to do the newly idle load balance.
11258 *
11259 * However, we bail out if we already have tasks or a wakeup pending,
11260 * to optimize wakeup latency.
11261 */
11262 if (env->idle == CPU_NEWLY_IDLE) {
11263 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending)
11264 return 0;
11265 return 1;
11266 }
11267
11268 cpumask_copy(swb_cpus, group_balance_mask(sg));
11269 /* Try to find first idle CPU */
11270 for_each_cpu_and(cpu, swb_cpus, env->cpus) {
11271 if (!idle_cpu(cpu))
11272 continue;
11273
11274 /*
11275 * Don't balance to idle SMT in busy core right away when
11276 * balancing cores, but remember the first idle SMT CPU for
11277 * later consideration. Find CPU on an idle core first.
11278 */
11279 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) {
11280 if (idle_smt == -1)
11281 idle_smt = cpu;
11282 /*
11283 * If the core is not idle, and first SMT sibling which is
11284 * idle has been found, then its not needed to check other
11285 * SMT siblings for idleness:
11286 */
11287 #ifdef CONFIG_SCHED_SMT
11288 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu));
11289 #endif
11290 continue;
11291 }
11292
11293 /*
11294 * Are we the first idle core in a non-SMT domain or higher,
11295 * or the first idle CPU in a SMT domain?
11296 */
11297 return cpu == env->dst_cpu;
11298 }
11299
11300 /* Are we the first idle CPU with busy siblings? */
11301 if (idle_smt != -1)
11302 return idle_smt == env->dst_cpu;
11303
11304 /* Are we the first CPU of this group ? */
11305 return group_balance_cpu(sg) == env->dst_cpu;
11306 }
11307
11308 /*
11309 * Check this_cpu to ensure it is balanced within domain. Attempt to move
11310 * tasks if there is an imbalance.
11311 */
load_balance(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)11312 static int load_balance(int this_cpu, struct rq *this_rq,
11313 struct sched_domain *sd, enum cpu_idle_type idle,
11314 int *continue_balancing)
11315 {
11316 int ld_moved, cur_ld_moved, active_balance = 0;
11317 struct sched_domain *sd_parent = sd->parent;
11318 struct sched_group *group;
11319 struct rq *busiest;
11320 struct rq_flags rf;
11321 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
11322 struct lb_env env = {
11323 .sd = sd,
11324 .dst_cpu = this_cpu,
11325 .dst_rq = this_rq,
11326 .dst_grpmask = group_balance_mask(sd->groups),
11327 .idle = idle,
11328 .loop_break = SCHED_NR_MIGRATE_BREAK,
11329 .cpus = cpus,
11330 .fbq_type = all,
11331 .tasks = LIST_HEAD_INIT(env.tasks),
11332 };
11333
11334 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
11335
11336 schedstat_inc(sd->lb_count[idle]);
11337
11338 redo:
11339 if (!should_we_balance(&env)) {
11340 *continue_balancing = 0;
11341 goto out_balanced;
11342 }
11343
11344 group = find_busiest_group(&env);
11345 if (!group) {
11346 schedstat_inc(sd->lb_nobusyg[idle]);
11347 goto out_balanced;
11348 }
11349
11350 busiest = find_busiest_queue(&env, group);
11351 if (!busiest) {
11352 schedstat_inc(sd->lb_nobusyq[idle]);
11353 goto out_balanced;
11354 }
11355
11356 WARN_ON_ONCE(busiest == env.dst_rq);
11357
11358 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
11359
11360 env.src_cpu = busiest->cpu;
11361 env.src_rq = busiest;
11362
11363 ld_moved = 0;
11364 /* Clear this flag as soon as we find a pullable task */
11365 env.flags |= LBF_ALL_PINNED;
11366 if (busiest->nr_running > 1) {
11367 /*
11368 * Attempt to move tasks. If find_busiest_group has found
11369 * an imbalance but busiest->nr_running <= 1, the group is
11370 * still unbalanced. ld_moved simply stays zero, so it is
11371 * correctly treated as an imbalance.
11372 */
11373 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
11374
11375 more_balance:
11376 rq_lock_irqsave(busiest, &rf);
11377 update_rq_clock(busiest);
11378
11379 /*
11380 * cur_ld_moved - load moved in current iteration
11381 * ld_moved - cumulative load moved across iterations
11382 */
11383 cur_ld_moved = detach_tasks(&env);
11384
11385 /*
11386 * We've detached some tasks from busiest_rq. Every
11387 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
11388 * unlock busiest->lock, and we are able to be sure
11389 * that nobody can manipulate the tasks in parallel.
11390 * See task_rq_lock() family for the details.
11391 */
11392
11393 rq_unlock(busiest, &rf);
11394
11395 if (cur_ld_moved) {
11396 attach_tasks(&env);
11397 ld_moved += cur_ld_moved;
11398 }
11399
11400 local_irq_restore(rf.flags);
11401
11402 if (env.flags & LBF_NEED_BREAK) {
11403 env.flags &= ~LBF_NEED_BREAK;
11404 /* Stop if we tried all running tasks */
11405 if (env.loop < busiest->nr_running)
11406 goto more_balance;
11407 }
11408
11409 /*
11410 * Revisit (affine) tasks on src_cpu that couldn't be moved to
11411 * us and move them to an alternate dst_cpu in our sched_group
11412 * where they can run. The upper limit on how many times we
11413 * iterate on same src_cpu is dependent on number of CPUs in our
11414 * sched_group.
11415 *
11416 * This changes load balance semantics a bit on who can move
11417 * load to a given_cpu. In addition to the given_cpu itself
11418 * (or a ilb_cpu acting on its behalf where given_cpu is
11419 * nohz-idle), we now have balance_cpu in a position to move
11420 * load to given_cpu. In rare situations, this may cause
11421 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
11422 * _independently_ and at _same_ time to move some load to
11423 * given_cpu) causing excess load to be moved to given_cpu.
11424 * This however should not happen so much in practice and
11425 * moreover subsequent load balance cycles should correct the
11426 * excess load moved.
11427 */
11428 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
11429
11430 /* Prevent to re-select dst_cpu via env's CPUs */
11431 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
11432
11433 env.dst_rq = cpu_rq(env.new_dst_cpu);
11434 env.dst_cpu = env.new_dst_cpu;
11435 env.flags &= ~LBF_DST_PINNED;
11436 env.loop = 0;
11437 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11438
11439 /*
11440 * Go back to "more_balance" rather than "redo" since we
11441 * need to continue with same src_cpu.
11442 */
11443 goto more_balance;
11444 }
11445
11446 /*
11447 * We failed to reach balance because of affinity.
11448 */
11449 if (sd_parent) {
11450 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11451
11452 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
11453 *group_imbalance = 1;
11454 }
11455
11456 /* All tasks on this runqueue were pinned by CPU affinity */
11457 if (unlikely(env.flags & LBF_ALL_PINNED)) {
11458 __cpumask_clear_cpu(cpu_of(busiest), cpus);
11459 /*
11460 * Attempting to continue load balancing at the current
11461 * sched_domain level only makes sense if there are
11462 * active CPUs remaining as possible busiest CPUs to
11463 * pull load from which are not contained within the
11464 * destination group that is receiving any migrated
11465 * load.
11466 */
11467 if (!cpumask_subset(cpus, env.dst_grpmask)) {
11468 env.loop = 0;
11469 env.loop_break = SCHED_NR_MIGRATE_BREAK;
11470 goto redo;
11471 }
11472 goto out_all_pinned;
11473 }
11474 }
11475
11476 if (!ld_moved) {
11477 schedstat_inc(sd->lb_failed[idle]);
11478 /*
11479 * Increment the failure counter only on periodic balance.
11480 * We do not want newidle balance, which can be very
11481 * frequent, pollute the failure counter causing
11482 * excessive cache_hot migrations and active balances.
11483 */
11484 if (idle != CPU_NEWLY_IDLE)
11485 sd->nr_balance_failed++;
11486
11487 if (need_active_balance(&env)) {
11488 unsigned long flags;
11489
11490 raw_spin_rq_lock_irqsave(busiest, flags);
11491
11492 /*
11493 * Don't kick the active_load_balance_cpu_stop,
11494 * if the curr task on busiest CPU can't be
11495 * moved to this_cpu:
11496 */
11497 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
11498 raw_spin_rq_unlock_irqrestore(busiest, flags);
11499 goto out_one_pinned;
11500 }
11501
11502 /* Record that we found at least one task that could run on this_cpu */
11503 env.flags &= ~LBF_ALL_PINNED;
11504
11505 /*
11506 * ->active_balance synchronizes accesses to
11507 * ->active_balance_work. Once set, it's cleared
11508 * only after active load balance is finished.
11509 */
11510 if (!busiest->active_balance) {
11511 busiest->active_balance = 1;
11512 busiest->push_cpu = this_cpu;
11513 active_balance = 1;
11514 }
11515
11516 preempt_disable();
11517 raw_spin_rq_unlock_irqrestore(busiest, flags);
11518 if (active_balance) {
11519 stop_one_cpu_nowait(cpu_of(busiest),
11520 active_load_balance_cpu_stop, busiest,
11521 &busiest->active_balance_work);
11522 }
11523 preempt_enable();
11524 }
11525 } else {
11526 sd->nr_balance_failed = 0;
11527 }
11528
11529 if (likely(!active_balance) || need_active_balance(&env)) {
11530 /* We were unbalanced, so reset the balancing interval */
11531 sd->balance_interval = sd->min_interval;
11532 }
11533
11534 goto out;
11535
11536 out_balanced:
11537 /*
11538 * We reach balance although we may have faced some affinity
11539 * constraints. Clear the imbalance flag only if other tasks got
11540 * a chance to move and fix the imbalance.
11541 */
11542 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
11543 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
11544
11545 if (*group_imbalance)
11546 *group_imbalance = 0;
11547 }
11548
11549 out_all_pinned:
11550 /*
11551 * We reach balance because all tasks are pinned at this level so
11552 * we can't migrate them. Let the imbalance flag set so parent level
11553 * can try to migrate them.
11554 */
11555 schedstat_inc(sd->lb_balanced[idle]);
11556
11557 sd->nr_balance_failed = 0;
11558
11559 out_one_pinned:
11560 ld_moved = 0;
11561
11562 /*
11563 * newidle_balance() disregards balance intervals, so we could
11564 * repeatedly reach this code, which would lead to balance_interval
11565 * skyrocketing in a short amount of time. Skip the balance_interval
11566 * increase logic to avoid that.
11567 */
11568 if (env.idle == CPU_NEWLY_IDLE)
11569 goto out;
11570
11571 /* tune up the balancing interval */
11572 if ((env.flags & LBF_ALL_PINNED &&
11573 sd->balance_interval < MAX_PINNED_INTERVAL) ||
11574 sd->balance_interval < sd->max_interval)
11575 sd->balance_interval *= 2;
11576 out:
11577 return ld_moved;
11578 }
11579
11580 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)11581 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
11582 {
11583 unsigned long interval = sd->balance_interval;
11584
11585 if (cpu_busy)
11586 interval *= sd->busy_factor;
11587
11588 /* scale ms to jiffies */
11589 interval = msecs_to_jiffies(interval);
11590
11591 /*
11592 * Reduce likelihood of busy balancing at higher domains racing with
11593 * balancing at lower domains by preventing their balancing periods
11594 * from being multiples of each other.
11595 */
11596 if (cpu_busy)
11597 interval -= 1;
11598
11599 interval = clamp(interval, 1UL, max_load_balance_interval);
11600
11601 return interval;
11602 }
11603
11604 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)11605 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
11606 {
11607 unsigned long interval, next;
11608
11609 /* used by idle balance, so cpu_busy = 0 */
11610 interval = get_sd_balance_interval(sd, 0);
11611 next = sd->last_balance + interval;
11612
11613 if (time_after(*next_balance, next))
11614 *next_balance = next;
11615 }
11616
11617 /*
11618 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
11619 * running tasks off the busiest CPU onto idle CPUs. It requires at
11620 * least 1 task to be running on each physical CPU where possible, and
11621 * avoids physical / logical imbalances.
11622 */
active_load_balance_cpu_stop(void * data)11623 static int active_load_balance_cpu_stop(void *data)
11624 {
11625 struct rq *busiest_rq = data;
11626 int busiest_cpu = cpu_of(busiest_rq);
11627 int target_cpu = busiest_rq->push_cpu;
11628 struct rq *target_rq = cpu_rq(target_cpu);
11629 struct sched_domain *sd;
11630 struct task_struct *p = NULL;
11631 struct rq_flags rf;
11632
11633 rq_lock_irq(busiest_rq, &rf);
11634 /*
11635 * Between queueing the stop-work and running it is a hole in which
11636 * CPUs can become inactive. We should not move tasks from or to
11637 * inactive CPUs.
11638 */
11639 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
11640 goto out_unlock;
11641
11642 /* Make sure the requested CPU hasn't gone down in the meantime: */
11643 if (unlikely(busiest_cpu != smp_processor_id() ||
11644 !busiest_rq->active_balance))
11645 goto out_unlock;
11646
11647 /* Is there any task to move? */
11648 if (busiest_rq->nr_running <= 1)
11649 goto out_unlock;
11650
11651 /*
11652 * This condition is "impossible", if it occurs
11653 * we need to fix it. Originally reported by
11654 * Bjorn Helgaas on a 128-CPU setup.
11655 */
11656 WARN_ON_ONCE(busiest_rq == target_rq);
11657
11658 /* Search for an sd spanning us and the target CPU. */
11659 rcu_read_lock();
11660 for_each_domain(target_cpu, sd) {
11661 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
11662 break;
11663 }
11664
11665 if (likely(sd)) {
11666 struct lb_env env = {
11667 .sd = sd,
11668 .dst_cpu = target_cpu,
11669 .dst_rq = target_rq,
11670 .src_cpu = busiest_rq->cpu,
11671 .src_rq = busiest_rq,
11672 .idle = CPU_IDLE,
11673 .flags = LBF_ACTIVE_LB,
11674 };
11675
11676 schedstat_inc(sd->alb_count);
11677 update_rq_clock(busiest_rq);
11678
11679 p = detach_one_task(&env);
11680 if (p) {
11681 schedstat_inc(sd->alb_pushed);
11682 /* Active balancing done, reset the failure counter. */
11683 sd->nr_balance_failed = 0;
11684 } else {
11685 schedstat_inc(sd->alb_failed);
11686 }
11687 }
11688 rcu_read_unlock();
11689 out_unlock:
11690 busiest_rq->active_balance = 0;
11691 rq_unlock(busiest_rq, &rf);
11692
11693 if (p)
11694 attach_one_task(target_rq, p);
11695
11696 local_irq_enable();
11697
11698 return 0;
11699 }
11700
11701 static DEFINE_SPINLOCK(balancing);
11702
11703 /*
11704 * Scale the max load_balance interval with the number of CPUs in the system.
11705 * This trades load-balance latency on larger machines for less cross talk.
11706 */
update_max_interval(void)11707 void update_max_interval(void)
11708 {
11709 max_load_balance_interval = HZ*num_online_cpus()/10;
11710 }
11711
update_newidle_cost(struct sched_domain * sd,u64 cost)11712 static inline bool update_newidle_cost(struct sched_domain *sd, u64 cost)
11713 {
11714 if (cost > sd->max_newidle_lb_cost) {
11715 /*
11716 * Track max cost of a domain to make sure to not delay the
11717 * next wakeup on the CPU.
11718 */
11719 sd->max_newidle_lb_cost = cost;
11720 sd->last_decay_max_lb_cost = jiffies;
11721 } else if (time_after(jiffies, sd->last_decay_max_lb_cost + HZ)) {
11722 /*
11723 * Decay the newidle max times by ~1% per second to ensure that
11724 * it is not outdated and the current max cost is actually
11725 * shorter.
11726 */
11727 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256;
11728 sd->last_decay_max_lb_cost = jiffies;
11729
11730 return true;
11731 }
11732
11733 return false;
11734 }
11735
11736 /*
11737 * It checks each scheduling domain to see if it is due to be balanced,
11738 * and initiates a balancing operation if so.
11739 *
11740 * Balancing parameters are set up in init_sched_domains.
11741 */
rebalance_domains(struct rq * rq,enum cpu_idle_type idle)11742 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
11743 {
11744 int continue_balancing = 1;
11745 int cpu = rq->cpu;
11746 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11747 unsigned long interval;
11748 struct sched_domain *sd;
11749 /* Earliest time when we have to do rebalance again */
11750 unsigned long next_balance = jiffies + 60*HZ;
11751 int update_next_balance = 0;
11752 int need_serialize, need_decay = 0;
11753 u64 max_cost = 0;
11754
11755 rcu_read_lock();
11756 for_each_domain(cpu, sd) {
11757 /*
11758 * Decay the newidle max times here because this is a regular
11759 * visit to all the domains.
11760 */
11761 need_decay = update_newidle_cost(sd, 0);
11762 max_cost += sd->max_newidle_lb_cost;
11763
11764 /*
11765 * Stop the load balance at this level. There is another
11766 * CPU in our sched group which is doing load balancing more
11767 * actively.
11768 */
11769 if (!continue_balancing) {
11770 if (need_decay)
11771 continue;
11772 break;
11773 }
11774
11775 interval = get_sd_balance_interval(sd, busy);
11776
11777 need_serialize = sd->flags & SD_SERIALIZE;
11778 if (need_serialize) {
11779 if (!spin_trylock(&balancing))
11780 goto out;
11781 }
11782
11783 if (time_after_eq(jiffies, sd->last_balance + interval)) {
11784 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
11785 /*
11786 * The LBF_DST_PINNED logic could have changed
11787 * env->dst_cpu, so we can't know our idle
11788 * state even if we migrated tasks. Update it.
11789 */
11790 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
11791 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
11792 }
11793 sd->last_balance = jiffies;
11794 interval = get_sd_balance_interval(sd, busy);
11795 }
11796 if (need_serialize)
11797 spin_unlock(&balancing);
11798 out:
11799 if (time_after(next_balance, sd->last_balance + interval)) {
11800 next_balance = sd->last_balance + interval;
11801 update_next_balance = 1;
11802 }
11803 }
11804 if (need_decay) {
11805 /*
11806 * Ensure the rq-wide value also decays but keep it at a
11807 * reasonable floor to avoid funnies with rq->avg_idle.
11808 */
11809 rq->max_idle_balance_cost =
11810 max((u64)sysctl_sched_migration_cost, max_cost);
11811 }
11812 rcu_read_unlock();
11813
11814 /*
11815 * next_balance will be updated only when there is a need.
11816 * When the cpu is attached to null domain for ex, it will not be
11817 * updated.
11818 */
11819 if (likely(update_next_balance))
11820 rq->next_balance = next_balance;
11821
11822 }
11823
on_null_domain(struct rq * rq)11824 static inline int on_null_domain(struct rq *rq)
11825 {
11826 return unlikely(!rcu_dereference_sched(rq->sd));
11827 }
11828
11829 #ifdef CONFIG_NO_HZ_COMMON
11830 /*
11831 * idle load balancing details
11832 * - When one of the busy CPUs notice that there may be an idle rebalancing
11833 * needed, they will kick the idle load balancer, which then does idle
11834 * load balancing for all the idle CPUs.
11835 * - HK_TYPE_MISC CPUs are used for this task, because HK_TYPE_SCHED not set
11836 * anywhere yet.
11837 */
11838
find_new_ilb(void)11839 static inline int find_new_ilb(void)
11840 {
11841 int ilb;
11842 const struct cpumask *hk_mask;
11843
11844 hk_mask = housekeeping_cpumask(HK_TYPE_MISC);
11845
11846 for_each_cpu_and(ilb, nohz.idle_cpus_mask, hk_mask) {
11847
11848 if (ilb == smp_processor_id())
11849 continue;
11850
11851 if (idle_cpu(ilb))
11852 return ilb;
11853 }
11854
11855 return nr_cpu_ids;
11856 }
11857
11858 /*
11859 * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
11860 * idle CPU in the HK_TYPE_MISC housekeeping set (if there is one).
11861 */
kick_ilb(unsigned int flags)11862 static void kick_ilb(unsigned int flags)
11863 {
11864 int ilb_cpu;
11865
11866 /*
11867 * Increase nohz.next_balance only when if full ilb is triggered but
11868 * not if we only update stats.
11869 */
11870 if (flags & NOHZ_BALANCE_KICK)
11871 nohz.next_balance = jiffies+1;
11872
11873 ilb_cpu = find_new_ilb();
11874
11875 if (ilb_cpu >= nr_cpu_ids)
11876 return;
11877
11878 /*
11879 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
11880 * the first flag owns it; cleared by nohz_csd_func().
11881 */
11882 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
11883 if (flags & NOHZ_KICK_MASK)
11884 return;
11885
11886 /*
11887 * This way we generate an IPI on the target CPU which
11888 * is idle. And the softirq performing nohz idle load balance
11889 * will be run before returning from the IPI.
11890 */
11891 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
11892 }
11893
11894 /*
11895 * Current decision point for kicking the idle load balancer in the presence
11896 * of idle CPUs in the system.
11897 */
nohz_balancer_kick(struct rq * rq)11898 static void nohz_balancer_kick(struct rq *rq)
11899 {
11900 unsigned long now = jiffies;
11901 struct sched_domain_shared *sds;
11902 struct sched_domain *sd;
11903 int nr_busy, i, cpu = rq->cpu;
11904 unsigned int flags = 0;
11905
11906 if (unlikely(rq->idle_balance))
11907 return;
11908
11909 /*
11910 * We may be recently in ticked or tickless idle mode. At the first
11911 * busy tick after returning from idle, we will update the busy stats.
11912 */
11913 nohz_balance_exit_idle(rq);
11914
11915 /*
11916 * None are in tickless mode and hence no need for NOHZ idle load
11917 * balancing.
11918 */
11919 if (likely(!atomic_read(&nohz.nr_cpus)))
11920 return;
11921
11922 if (READ_ONCE(nohz.has_blocked) &&
11923 time_after(now, READ_ONCE(nohz.next_blocked)))
11924 flags = NOHZ_STATS_KICK;
11925
11926 if (time_before(now, nohz.next_balance))
11927 goto out;
11928
11929 if (rq->nr_running >= 2) {
11930 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11931 goto out;
11932 }
11933
11934 rcu_read_lock();
11935
11936 sd = rcu_dereference(rq->sd);
11937 if (sd) {
11938 /*
11939 * If there's a CFS task and the current CPU has reduced
11940 * capacity; kick the ILB to see if there's a better CPU to run
11941 * on.
11942 */
11943 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
11944 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11945 goto unlock;
11946 }
11947 }
11948
11949 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
11950 if (sd) {
11951 /*
11952 * When ASYM_PACKING; see if there's a more preferred CPU
11953 * currently idle; in which case, kick the ILB to move tasks
11954 * around.
11955 *
11956 * When balancing betwen cores, all the SMT siblings of the
11957 * preferred CPU must be idle.
11958 */
11959 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) {
11960 if (sched_use_asym_prio(sd, i) &&
11961 sched_asym_prefer(i, cpu)) {
11962 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11963 goto unlock;
11964 }
11965 }
11966 }
11967
11968 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
11969 if (sd) {
11970 /*
11971 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
11972 * to run the misfit task on.
11973 */
11974 if (check_misfit_status(rq, sd)) {
11975 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
11976 goto unlock;
11977 }
11978
11979 /*
11980 * For asymmetric systems, we do not want to nicely balance
11981 * cache use, instead we want to embrace asymmetry and only
11982 * ensure tasks have enough CPU capacity.
11983 *
11984 * Skip the LLC logic because it's not relevant in that case.
11985 */
11986 goto unlock;
11987 }
11988
11989 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
11990 if (sds) {
11991 /*
11992 * If there is an imbalance between LLC domains (IOW we could
11993 * increase the overall cache use), we need some less-loaded LLC
11994 * domain to pull some load. Likewise, we may need to spread
11995 * load within the current LLC domain (e.g. packed SMT cores but
11996 * other CPUs are idle). We can't really know from here how busy
11997 * the others are - so just get a nohz balance going if it looks
11998 * like this LLC domain has tasks we could move.
11999 */
12000 nr_busy = atomic_read(&sds->nr_busy_cpus);
12001 if (nr_busy > 1) {
12002 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK;
12003 goto unlock;
12004 }
12005 }
12006 unlock:
12007 rcu_read_unlock();
12008 out:
12009 if (READ_ONCE(nohz.needs_update))
12010 flags |= NOHZ_NEXT_KICK;
12011
12012 if (flags)
12013 kick_ilb(flags);
12014 }
12015
set_cpu_sd_state_busy(int cpu)12016 static void set_cpu_sd_state_busy(int cpu)
12017 {
12018 struct sched_domain *sd;
12019
12020 rcu_read_lock();
12021 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12022
12023 if (!sd || !sd->nohz_idle)
12024 goto unlock;
12025 sd->nohz_idle = 0;
12026
12027 atomic_inc(&sd->shared->nr_busy_cpus);
12028 unlock:
12029 rcu_read_unlock();
12030 }
12031
nohz_balance_exit_idle(struct rq * rq)12032 void nohz_balance_exit_idle(struct rq *rq)
12033 {
12034 SCHED_WARN_ON(rq != this_rq());
12035
12036 if (likely(!rq->nohz_tick_stopped))
12037 return;
12038
12039 rq->nohz_tick_stopped = 0;
12040 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
12041 atomic_dec(&nohz.nr_cpus);
12042
12043 set_cpu_sd_state_busy(rq->cpu);
12044 }
12045
set_cpu_sd_state_idle(int cpu)12046 static void set_cpu_sd_state_idle(int cpu)
12047 {
12048 struct sched_domain *sd;
12049
12050 rcu_read_lock();
12051 sd = rcu_dereference(per_cpu(sd_llc, cpu));
12052
12053 if (!sd || sd->nohz_idle)
12054 goto unlock;
12055 sd->nohz_idle = 1;
12056
12057 atomic_dec(&sd->shared->nr_busy_cpus);
12058 unlock:
12059 rcu_read_unlock();
12060 }
12061
12062 /*
12063 * This routine will record that the CPU is going idle with tick stopped.
12064 * This info will be used in performing idle load balancing in the future.
12065 */
nohz_balance_enter_idle(int cpu)12066 void nohz_balance_enter_idle(int cpu)
12067 {
12068 struct rq *rq = cpu_rq(cpu);
12069
12070 SCHED_WARN_ON(cpu != smp_processor_id());
12071
12072 /* If this CPU is going down, then nothing needs to be done: */
12073 if (!cpu_active(cpu))
12074 return;
12075
12076 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
12077 if (!housekeeping_cpu(cpu, HK_TYPE_SCHED))
12078 return;
12079
12080 /*
12081 * Can be set safely without rq->lock held
12082 * If a clear happens, it will have evaluated last additions because
12083 * rq->lock is held during the check and the clear
12084 */
12085 rq->has_blocked_load = 1;
12086
12087 /*
12088 * The tick is still stopped but load could have been added in the
12089 * meantime. We set the nohz.has_blocked flag to trig a check of the
12090 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
12091 * of nohz.has_blocked can only happen after checking the new load
12092 */
12093 if (rq->nohz_tick_stopped)
12094 goto out;
12095
12096 /* If we're a completely isolated CPU, we don't play: */
12097 if (on_null_domain(rq))
12098 return;
12099
12100 rq->nohz_tick_stopped = 1;
12101
12102 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
12103 atomic_inc(&nohz.nr_cpus);
12104
12105 /*
12106 * Ensures that if nohz_idle_balance() fails to observe our
12107 * @idle_cpus_mask store, it must observe the @has_blocked
12108 * and @needs_update stores.
12109 */
12110 smp_mb__after_atomic();
12111
12112 set_cpu_sd_state_idle(cpu);
12113
12114 WRITE_ONCE(nohz.needs_update, 1);
12115 out:
12116 /*
12117 * Each time a cpu enter idle, we assume that it has blocked load and
12118 * enable the periodic update of the load of idle cpus
12119 */
12120 WRITE_ONCE(nohz.has_blocked, 1);
12121 }
12122
update_nohz_stats(struct rq * rq)12123 static bool update_nohz_stats(struct rq *rq)
12124 {
12125 unsigned int cpu = rq->cpu;
12126
12127 if (!rq->has_blocked_load)
12128 return false;
12129
12130 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
12131 return false;
12132
12133 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick)))
12134 return true;
12135
12136 update_blocked_averages(cpu);
12137
12138 return rq->has_blocked_load;
12139 }
12140
12141 /*
12142 * Internal function that runs load balance for all idle cpus. The load balance
12143 * can be a simple update of blocked load or a complete load balance with
12144 * tasks movement depending of flags.
12145 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags)12146 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags)
12147 {
12148 /* Earliest time when we have to do rebalance again */
12149 unsigned long now = jiffies;
12150 unsigned long next_balance = now + 60*HZ;
12151 bool has_blocked_load = false;
12152 int update_next_balance = 0;
12153 int this_cpu = this_rq->cpu;
12154 int balance_cpu;
12155 struct rq *rq;
12156
12157 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
12158
12159 /*
12160 * We assume there will be no idle load after this update and clear
12161 * the has_blocked flag. If a cpu enters idle in the mean time, it will
12162 * set the has_blocked flag and trigger another update of idle load.
12163 * Because a cpu that becomes idle, is added to idle_cpus_mask before
12164 * setting the flag, we are sure to not clear the state and not
12165 * check the load of an idle cpu.
12166 *
12167 * Same applies to idle_cpus_mask vs needs_update.
12168 */
12169 if (flags & NOHZ_STATS_KICK)
12170 WRITE_ONCE(nohz.has_blocked, 0);
12171 if (flags & NOHZ_NEXT_KICK)
12172 WRITE_ONCE(nohz.needs_update, 0);
12173
12174 /*
12175 * Ensures that if we miss the CPU, we must see the has_blocked
12176 * store from nohz_balance_enter_idle().
12177 */
12178 smp_mb();
12179
12180 /*
12181 * Start with the next CPU after this_cpu so we will end with this_cpu and let a
12182 * chance for other idle cpu to pull load.
12183 */
12184 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) {
12185 if (!idle_cpu(balance_cpu))
12186 continue;
12187
12188 /*
12189 * If this CPU gets work to do, stop the load balancing
12190 * work being done for other CPUs. Next load
12191 * balancing owner will pick it up.
12192 */
12193 if (need_resched()) {
12194 if (flags & NOHZ_STATS_KICK)
12195 has_blocked_load = true;
12196 if (flags & NOHZ_NEXT_KICK)
12197 WRITE_ONCE(nohz.needs_update, 1);
12198 goto abort;
12199 }
12200
12201 rq = cpu_rq(balance_cpu);
12202
12203 if (flags & NOHZ_STATS_KICK)
12204 has_blocked_load |= update_nohz_stats(rq);
12205
12206 /*
12207 * If time for next balance is due,
12208 * do the balance.
12209 */
12210 if (time_after_eq(jiffies, rq->next_balance)) {
12211 struct rq_flags rf;
12212
12213 rq_lock_irqsave(rq, &rf);
12214 update_rq_clock(rq);
12215 rq_unlock_irqrestore(rq, &rf);
12216
12217 if (flags & NOHZ_BALANCE_KICK)
12218 rebalance_domains(rq, CPU_IDLE);
12219 }
12220
12221 if (time_after(next_balance, rq->next_balance)) {
12222 next_balance = rq->next_balance;
12223 update_next_balance = 1;
12224 }
12225 }
12226
12227 /*
12228 * next_balance will be updated only when there is a need.
12229 * When the CPU is attached to null domain for ex, it will not be
12230 * updated.
12231 */
12232 if (likely(update_next_balance))
12233 nohz.next_balance = next_balance;
12234
12235 if (flags & NOHZ_STATS_KICK)
12236 WRITE_ONCE(nohz.next_blocked,
12237 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
12238
12239 abort:
12240 /* There is still blocked load, enable periodic update */
12241 if (has_blocked_load)
12242 WRITE_ONCE(nohz.has_blocked, 1);
12243 }
12244
12245 /*
12246 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
12247 * rebalancing for all the cpus for whom scheduler ticks are stopped.
12248 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12249 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12250 {
12251 unsigned int flags = this_rq->nohz_idle_balance;
12252
12253 if (!flags)
12254 return false;
12255
12256 this_rq->nohz_idle_balance = 0;
12257
12258 if (idle != CPU_IDLE)
12259 return false;
12260
12261 _nohz_idle_balance(this_rq, flags);
12262
12263 return true;
12264 }
12265
12266 /*
12267 * Check if we need to run the ILB for updating blocked load before entering
12268 * idle state.
12269 */
nohz_run_idle_balance(int cpu)12270 void nohz_run_idle_balance(int cpu)
12271 {
12272 unsigned int flags;
12273
12274 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu));
12275
12276 /*
12277 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen
12278 * (ie NOHZ_STATS_KICK set) and will do the same.
12279 */
12280 if ((flags == NOHZ_NEWILB_KICK) && !need_resched())
12281 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK);
12282 }
12283
nohz_newidle_balance(struct rq * this_rq)12284 static void nohz_newidle_balance(struct rq *this_rq)
12285 {
12286 int this_cpu = this_rq->cpu;
12287
12288 /*
12289 * This CPU doesn't want to be disturbed by scheduler
12290 * housekeeping
12291 */
12292 if (!housekeeping_cpu(this_cpu, HK_TYPE_SCHED))
12293 return;
12294
12295 /* Will wake up very soon. No time for doing anything else*/
12296 if (this_rq->avg_idle < sysctl_sched_migration_cost)
12297 return;
12298
12299 /* Don't need to update blocked load of idle CPUs*/
12300 if (!READ_ONCE(nohz.has_blocked) ||
12301 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
12302 return;
12303
12304 /*
12305 * Set the need to trigger ILB in order to update blocked load
12306 * before entering idle state.
12307 */
12308 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu));
12309 }
12310
12311 #else /* !CONFIG_NO_HZ_COMMON */
nohz_balancer_kick(struct rq * rq)12312 static inline void nohz_balancer_kick(struct rq *rq) { }
12313
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)12314 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
12315 {
12316 return false;
12317 }
12318
nohz_newidle_balance(struct rq * this_rq)12319 static inline void nohz_newidle_balance(struct rq *this_rq) { }
12320 #endif /* CONFIG_NO_HZ_COMMON */
12321
12322 /*
12323 * newidle_balance is called by schedule() if this_cpu is about to become
12324 * idle. Attempts to pull tasks from other CPUs.
12325 *
12326 * Returns:
12327 * < 0 - we released the lock and there are !fair tasks present
12328 * 0 - failed, no new tasks
12329 * > 0 - success, new (fair) tasks present
12330 */
newidle_balance(struct rq * this_rq,struct rq_flags * rf)12331 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
12332 {
12333 unsigned long next_balance = jiffies + HZ;
12334 int this_cpu = this_rq->cpu;
12335 u64 t0, t1, curr_cost = 0;
12336 struct sched_domain *sd;
12337 int pulled_task = 0;
12338
12339 update_misfit_status(NULL, this_rq);
12340
12341 /*
12342 * There is a task waiting to run. No need to search for one.
12343 * Return 0; the task will be enqueued when switching to idle.
12344 */
12345 if (this_rq->ttwu_pending)
12346 return 0;
12347
12348 /*
12349 * We must set idle_stamp _before_ calling idle_balance(), such that we
12350 * measure the duration of idle_balance() as idle time.
12351 */
12352 this_rq->idle_stamp = rq_clock(this_rq);
12353
12354 /*
12355 * Do not pull tasks towards !active CPUs...
12356 */
12357 if (!cpu_active(this_cpu))
12358 return 0;
12359
12360 /*
12361 * This is OK, because current is on_cpu, which avoids it being picked
12362 * for load-balance and preemption/IRQs are still disabled avoiding
12363 * further scheduler activity on it and we're being very careful to
12364 * re-start the picking loop.
12365 */
12366 rq_unpin_lock(this_rq, rf);
12367
12368 rcu_read_lock();
12369 sd = rcu_dereference_check_sched_domain(this_rq->sd);
12370
12371 if (!READ_ONCE(this_rq->rd->overload) ||
12372 (sd && this_rq->avg_idle < sd->max_newidle_lb_cost)) {
12373
12374 if (sd)
12375 update_next_balance(sd, &next_balance);
12376 rcu_read_unlock();
12377
12378 goto out;
12379 }
12380 rcu_read_unlock();
12381
12382 raw_spin_rq_unlock(this_rq);
12383
12384 t0 = sched_clock_cpu(this_cpu);
12385 update_blocked_averages(this_cpu);
12386
12387 rcu_read_lock();
12388 for_each_domain(this_cpu, sd) {
12389 int continue_balancing = 1;
12390 u64 domain_cost;
12391
12392 update_next_balance(sd, &next_balance);
12393
12394 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost)
12395 break;
12396
12397 if (sd->flags & SD_BALANCE_NEWIDLE) {
12398
12399 pulled_task = load_balance(this_cpu, this_rq,
12400 sd, CPU_NEWLY_IDLE,
12401 &continue_balancing);
12402
12403 t1 = sched_clock_cpu(this_cpu);
12404 domain_cost = t1 - t0;
12405 update_newidle_cost(sd, domain_cost);
12406
12407 curr_cost += domain_cost;
12408 t0 = t1;
12409 }
12410
12411 /*
12412 * Stop searching for tasks to pull if there are
12413 * now runnable tasks on this rq.
12414 */
12415 if (pulled_task || this_rq->nr_running > 0 ||
12416 this_rq->ttwu_pending)
12417 break;
12418 }
12419 rcu_read_unlock();
12420
12421 raw_spin_rq_lock(this_rq);
12422
12423 if (curr_cost > this_rq->max_idle_balance_cost)
12424 this_rq->max_idle_balance_cost = curr_cost;
12425
12426 /*
12427 * While browsing the domains, we released the rq lock, a task could
12428 * have been enqueued in the meantime. Since we're not going idle,
12429 * pretend we pulled a task.
12430 */
12431 if (this_rq->cfs.h_nr_running && !pulled_task)
12432 pulled_task = 1;
12433
12434 /* Is there a task of a high priority class? */
12435 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
12436 pulled_task = -1;
12437
12438 out:
12439 /* Move the next balance forward */
12440 if (time_after(this_rq->next_balance, next_balance))
12441 this_rq->next_balance = next_balance;
12442
12443 if (pulled_task)
12444 this_rq->idle_stamp = 0;
12445 else
12446 nohz_newidle_balance(this_rq);
12447
12448 rq_repin_lock(this_rq, rf);
12449
12450 return pulled_task;
12451 }
12452
12453 /*
12454 * run_rebalance_domains is triggered when needed from the scheduler tick.
12455 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
12456 */
run_rebalance_domains(struct softirq_action * h)12457 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
12458 {
12459 struct rq *this_rq = this_rq();
12460 enum cpu_idle_type idle = this_rq->idle_balance ?
12461 CPU_IDLE : CPU_NOT_IDLE;
12462
12463 /*
12464 * If this CPU has a pending nohz_balance_kick, then do the
12465 * balancing on behalf of the other idle CPUs whose ticks are
12466 * stopped. Do nohz_idle_balance *before* rebalance_domains to
12467 * give the idle CPUs a chance to load balance. Else we may
12468 * load balance only within the local sched_domain hierarchy
12469 * and abort nohz_idle_balance altogether if we pull some load.
12470 */
12471 if (nohz_idle_balance(this_rq, idle))
12472 return;
12473
12474 /* normal load balance */
12475 update_blocked_averages(this_rq->cpu);
12476 rebalance_domains(this_rq, idle);
12477 }
12478
12479 /*
12480 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
12481 */
trigger_load_balance(struct rq * rq)12482 void trigger_load_balance(struct rq *rq)
12483 {
12484 /*
12485 * Don't need to rebalance while attached to NULL domain or
12486 * runqueue CPU is not active
12487 */
12488 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq))))
12489 return;
12490
12491 if (time_after_eq(jiffies, rq->next_balance))
12492 raise_softirq(SCHED_SOFTIRQ);
12493
12494 nohz_balancer_kick(rq);
12495 }
12496
rq_online_fair(struct rq * rq)12497 static void rq_online_fair(struct rq *rq)
12498 {
12499 update_sysctl();
12500
12501 update_runtime_enabled(rq);
12502 }
12503
rq_offline_fair(struct rq * rq)12504 static void rq_offline_fair(struct rq *rq)
12505 {
12506 update_sysctl();
12507
12508 /* Ensure any throttled groups are reachable by pick_next_task */
12509 unthrottle_offline_cfs_rqs(rq);
12510 }
12511
12512 #endif /* CONFIG_SMP */
12513
12514 #ifdef CONFIG_SCHED_CORE
12515 static inline bool
__entity_slice_used(struct sched_entity * se,int min_nr_tasks)12516 __entity_slice_used(struct sched_entity *se, int min_nr_tasks)
12517 {
12518 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime;
12519 u64 slice = se->slice;
12520
12521 return (rtime * min_nr_tasks > slice);
12522 }
12523
12524 #define MIN_NR_TASKS_DURING_FORCEIDLE 2
task_tick_core(struct rq * rq,struct task_struct * curr)12525 static inline void task_tick_core(struct rq *rq, struct task_struct *curr)
12526 {
12527 if (!sched_core_enabled(rq))
12528 return;
12529
12530 /*
12531 * If runqueue has only one task which used up its slice and
12532 * if the sibling is forced idle, then trigger schedule to
12533 * give forced idle task a chance.
12534 *
12535 * sched_slice() considers only this active rq and it gets the
12536 * whole slice. But during force idle, we have siblings acting
12537 * like a single runqueue and hence we need to consider runnable
12538 * tasks on this CPU and the forced idle CPU. Ideally, we should
12539 * go through the forced idle rq, but that would be a perf hit.
12540 * We can assume that the forced idle CPU has at least
12541 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check
12542 * if we need to give up the CPU.
12543 */
12544 if (rq->core->core_forceidle_count && rq->cfs.nr_running == 1 &&
12545 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE))
12546 resched_curr(rq);
12547 }
12548
12549 /*
12550 * se_fi_update - Update the cfs_rq->min_vruntime_fi in a CFS hierarchy if needed.
12551 */
se_fi_update(const struct sched_entity * se,unsigned int fi_seq,bool forceidle)12552 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq,
12553 bool forceidle)
12554 {
12555 for_each_sched_entity(se) {
12556 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12557
12558 if (forceidle) {
12559 if (cfs_rq->forceidle_seq == fi_seq)
12560 break;
12561 cfs_rq->forceidle_seq = fi_seq;
12562 }
12563
12564 cfs_rq->min_vruntime_fi = cfs_rq->min_vruntime;
12565 }
12566 }
12567
task_vruntime_update(struct rq * rq,struct task_struct * p,bool in_fi)12568 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi)
12569 {
12570 struct sched_entity *se = &p->se;
12571
12572 if (p->sched_class != &fair_sched_class)
12573 return;
12574
12575 se_fi_update(se, rq->core->core_forceidle_seq, in_fi);
12576 }
12577
cfs_prio_less(const struct task_struct * a,const struct task_struct * b,bool in_fi)12578 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b,
12579 bool in_fi)
12580 {
12581 struct rq *rq = task_rq(a);
12582 const struct sched_entity *sea = &a->se;
12583 const struct sched_entity *seb = &b->se;
12584 struct cfs_rq *cfs_rqa;
12585 struct cfs_rq *cfs_rqb;
12586 s64 delta;
12587
12588 SCHED_WARN_ON(task_rq(b)->core != rq->core);
12589
12590 #ifdef CONFIG_FAIR_GROUP_SCHED
12591 /*
12592 * Find an se in the hierarchy for tasks a and b, such that the se's
12593 * are immediate siblings.
12594 */
12595 while (sea->cfs_rq->tg != seb->cfs_rq->tg) {
12596 int sea_depth = sea->depth;
12597 int seb_depth = seb->depth;
12598
12599 if (sea_depth >= seb_depth)
12600 sea = parent_entity(sea);
12601 if (sea_depth <= seb_depth)
12602 seb = parent_entity(seb);
12603 }
12604
12605 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi);
12606 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi);
12607
12608 cfs_rqa = sea->cfs_rq;
12609 cfs_rqb = seb->cfs_rq;
12610 #else
12611 cfs_rqa = &task_rq(a)->cfs;
12612 cfs_rqb = &task_rq(b)->cfs;
12613 #endif
12614
12615 /*
12616 * Find delta after normalizing se's vruntime with its cfs_rq's
12617 * min_vruntime_fi, which would have been updated in prior calls
12618 * to se_fi_update().
12619 */
12620 delta = (s64)(sea->vruntime - seb->vruntime) +
12621 (s64)(cfs_rqb->min_vruntime_fi - cfs_rqa->min_vruntime_fi);
12622
12623 return delta > 0;
12624 }
12625
task_is_throttled_fair(struct task_struct * p,int cpu)12626 static int task_is_throttled_fair(struct task_struct *p, int cpu)
12627 {
12628 struct cfs_rq *cfs_rq;
12629
12630 #ifdef CONFIG_FAIR_GROUP_SCHED
12631 cfs_rq = task_group(p)->cfs_rq[cpu];
12632 #else
12633 cfs_rq = &cpu_rq(cpu)->cfs;
12634 #endif
12635 return throttled_hierarchy(cfs_rq);
12636 }
12637 #else
task_tick_core(struct rq * rq,struct task_struct * curr)12638 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {}
12639 #endif
12640
12641 /*
12642 * scheduler tick hitting a task of our scheduling class.
12643 *
12644 * NOTE: This function can be called remotely by the tick offload that
12645 * goes along full dynticks. Therefore no local assumption can be made
12646 * and everything must be accessed through the @rq and @curr passed in
12647 * parameters.
12648 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)12649 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
12650 {
12651 struct cfs_rq *cfs_rq;
12652 struct sched_entity *se = &curr->se;
12653
12654 for_each_sched_entity(se) {
12655 cfs_rq = cfs_rq_of(se);
12656 entity_tick(cfs_rq, se, queued);
12657 }
12658
12659 if (static_branch_unlikely(&sched_numa_balancing))
12660 task_tick_numa(rq, curr);
12661
12662 update_misfit_status(curr, rq);
12663 update_overutilized_status(task_rq(curr));
12664
12665 task_tick_core(rq, curr);
12666 }
12667
12668 /*
12669 * called on fork with the child task as argument from the parent's context
12670 * - child not yet on the tasklist
12671 * - preemption disabled
12672 */
task_fork_fair(struct task_struct * p)12673 static void task_fork_fair(struct task_struct *p)
12674 {
12675 struct sched_entity *se = &p->se, *curr;
12676 struct cfs_rq *cfs_rq;
12677 struct rq *rq = this_rq();
12678 struct rq_flags rf;
12679
12680 rq_lock(rq, &rf);
12681 update_rq_clock(rq);
12682
12683 cfs_rq = task_cfs_rq(current);
12684 curr = cfs_rq->curr;
12685 if (curr)
12686 update_curr(cfs_rq);
12687 place_entity(cfs_rq, se, ENQUEUE_INITIAL);
12688 rq_unlock(rq, &rf);
12689 }
12690
12691 /*
12692 * Priority of the task has changed. Check to see if we preempt
12693 * the current task.
12694 */
12695 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,int oldprio)12696 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
12697 {
12698 if (!task_on_rq_queued(p))
12699 return;
12700
12701 if (rq->cfs.nr_running == 1)
12702 return;
12703
12704 /*
12705 * Reschedule if we are currently running on this runqueue and
12706 * our priority decreased, or if we are not currently running on
12707 * this runqueue and our priority is higher than the current's
12708 */
12709 if (task_current(rq, p)) {
12710 if (p->prio > oldprio)
12711 resched_curr(rq);
12712 } else
12713 check_preempt_curr(rq, p, 0);
12714 }
12715
12716 #ifdef CONFIG_FAIR_GROUP_SCHED
12717 /*
12718 * Propagate the changes of the sched_entity across the tg tree to make it
12719 * visible to the root
12720 */
propagate_entity_cfs_rq(struct sched_entity * se)12721 static void propagate_entity_cfs_rq(struct sched_entity *se)
12722 {
12723 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12724
12725 if (cfs_rq_throttled(cfs_rq))
12726 return;
12727
12728 if (!throttled_hierarchy(cfs_rq))
12729 list_add_leaf_cfs_rq(cfs_rq);
12730
12731 /* Start to propagate at parent */
12732 se = se->parent;
12733
12734 for_each_sched_entity(se) {
12735 cfs_rq = cfs_rq_of(se);
12736
12737 update_load_avg(cfs_rq, se, UPDATE_TG);
12738
12739 if (cfs_rq_throttled(cfs_rq))
12740 break;
12741
12742 if (!throttled_hierarchy(cfs_rq))
12743 list_add_leaf_cfs_rq(cfs_rq);
12744 }
12745 }
12746 #else
propagate_entity_cfs_rq(struct sched_entity * se)12747 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
12748 #endif
12749
detach_entity_cfs_rq(struct sched_entity * se)12750 static void detach_entity_cfs_rq(struct sched_entity *se)
12751 {
12752 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12753
12754 #ifdef CONFIG_SMP
12755 /*
12756 * In case the task sched_avg hasn't been attached:
12757 * - A forked task which hasn't been woken up by wake_up_new_task().
12758 * - A task which has been woken up by try_to_wake_up() but is
12759 * waiting for actually being woken up by sched_ttwu_pending().
12760 */
12761 if (!se->avg.last_update_time)
12762 return;
12763 #endif
12764
12765 /* Catch up with the cfs_rq and remove our load when we leave */
12766 update_load_avg(cfs_rq, se, 0);
12767 detach_entity_load_avg(cfs_rq, se);
12768 update_tg_load_avg(cfs_rq);
12769 propagate_entity_cfs_rq(se);
12770 }
12771
attach_entity_cfs_rq(struct sched_entity * se)12772 static void attach_entity_cfs_rq(struct sched_entity *se)
12773 {
12774 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12775
12776 /* Synchronize entity with its cfs_rq */
12777 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
12778 attach_entity_load_avg(cfs_rq, se);
12779 update_tg_load_avg(cfs_rq);
12780 propagate_entity_cfs_rq(se);
12781 }
12782
detach_task_cfs_rq(struct task_struct * p)12783 static void detach_task_cfs_rq(struct task_struct *p)
12784 {
12785 struct sched_entity *se = &p->se;
12786
12787 detach_entity_cfs_rq(se);
12788 }
12789
attach_task_cfs_rq(struct task_struct * p)12790 static void attach_task_cfs_rq(struct task_struct *p)
12791 {
12792 struct sched_entity *se = &p->se;
12793
12794 attach_entity_cfs_rq(se);
12795 }
12796
switched_from_fair(struct rq * rq,struct task_struct * p)12797 static void switched_from_fair(struct rq *rq, struct task_struct *p)
12798 {
12799 detach_task_cfs_rq(p);
12800 }
12801
switched_to_fair(struct rq * rq,struct task_struct * p)12802 static void switched_to_fair(struct rq *rq, struct task_struct *p)
12803 {
12804 attach_task_cfs_rq(p);
12805
12806 if (task_on_rq_queued(p)) {
12807 /*
12808 * We were most likely switched from sched_rt, so
12809 * kick off the schedule if running, otherwise just see
12810 * if we can still preempt the current task.
12811 */
12812 if (task_current(rq, p))
12813 resched_curr(rq);
12814 else
12815 check_preempt_curr(rq, p, 0);
12816 }
12817 }
12818
12819 /* Account for a task changing its policy or group.
12820 *
12821 * This routine is mostly called to set cfs_rq->curr field when a task
12822 * migrates between groups/classes.
12823 */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)12824 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
12825 {
12826 struct sched_entity *se = &p->se;
12827
12828 #ifdef CONFIG_SMP
12829 if (task_on_rq_queued(p)) {
12830 /*
12831 * Move the next running task to the front of the list, so our
12832 * cfs_tasks list becomes MRU one.
12833 */
12834 list_move(&se->group_node, &rq->cfs_tasks);
12835 }
12836 #endif
12837
12838 for_each_sched_entity(se) {
12839 struct cfs_rq *cfs_rq = cfs_rq_of(se);
12840
12841 set_next_entity(cfs_rq, se);
12842 /* ensure bandwidth has been allocated on our new cfs_rq */
12843 account_cfs_rq_runtime(cfs_rq, 0);
12844 }
12845 }
12846
init_cfs_rq(struct cfs_rq * cfs_rq)12847 void init_cfs_rq(struct cfs_rq *cfs_rq)
12848 {
12849 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
12850 u64_u32_store(cfs_rq->min_vruntime, (u64)(-(1LL << 20)));
12851 #ifdef CONFIG_SMP
12852 raw_spin_lock_init(&cfs_rq->removed.lock);
12853 #endif
12854 }
12855
12856 #ifdef CONFIG_FAIR_GROUP_SCHED
task_change_group_fair(struct task_struct * p)12857 static void task_change_group_fair(struct task_struct *p)
12858 {
12859 /*
12860 * We couldn't detach or attach a forked task which
12861 * hasn't been woken up by wake_up_new_task().
12862 */
12863 if (READ_ONCE(p->__state) == TASK_NEW)
12864 return;
12865
12866 detach_task_cfs_rq(p);
12867
12868 #ifdef CONFIG_SMP
12869 /* Tell se's cfs_rq has been changed -- migrated */
12870 p->se.avg.last_update_time = 0;
12871 #endif
12872 set_task_rq(p, task_cpu(p));
12873 attach_task_cfs_rq(p);
12874 }
12875
free_fair_sched_group(struct task_group * tg)12876 void free_fair_sched_group(struct task_group *tg)
12877 {
12878 int i;
12879
12880 for_each_possible_cpu(i) {
12881 if (tg->cfs_rq)
12882 kfree(tg->cfs_rq[i]);
12883 if (tg->se)
12884 kfree(tg->se[i]);
12885 }
12886
12887 kfree(tg->cfs_rq);
12888 kfree(tg->se);
12889 }
12890
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)12891 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
12892 {
12893 struct sched_entity *se;
12894 struct cfs_rq *cfs_rq;
12895 int i;
12896
12897 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
12898 if (!tg->cfs_rq)
12899 goto err;
12900 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
12901 if (!tg->se)
12902 goto err;
12903
12904 tg->shares = NICE_0_LOAD;
12905
12906 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent));
12907
12908 for_each_possible_cpu(i) {
12909 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
12910 GFP_KERNEL, cpu_to_node(i));
12911 if (!cfs_rq)
12912 goto err;
12913
12914 se = kzalloc_node(sizeof(struct sched_entity_stats),
12915 GFP_KERNEL, cpu_to_node(i));
12916 if (!se)
12917 goto err_free_rq;
12918
12919 init_cfs_rq(cfs_rq);
12920 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
12921 init_entity_runnable_average(se);
12922 }
12923
12924 return 1;
12925
12926 err_free_rq:
12927 kfree(cfs_rq);
12928 err:
12929 return 0;
12930 }
12931
online_fair_sched_group(struct task_group * tg)12932 void online_fair_sched_group(struct task_group *tg)
12933 {
12934 struct sched_entity *se;
12935 struct rq_flags rf;
12936 struct rq *rq;
12937 int i;
12938
12939 for_each_possible_cpu(i) {
12940 rq = cpu_rq(i);
12941 se = tg->se[i];
12942 rq_lock_irq(rq, &rf);
12943 update_rq_clock(rq);
12944 attach_entity_cfs_rq(se);
12945 sync_throttle(tg, i);
12946 rq_unlock_irq(rq, &rf);
12947 }
12948 }
12949
unregister_fair_sched_group(struct task_group * tg)12950 void unregister_fair_sched_group(struct task_group *tg)
12951 {
12952 unsigned long flags;
12953 struct rq *rq;
12954 int cpu;
12955
12956 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
12957
12958 for_each_possible_cpu(cpu) {
12959 if (tg->se[cpu])
12960 remove_entity_load_avg(tg->se[cpu]);
12961
12962 /*
12963 * Only empty task groups can be destroyed; so we can speculatively
12964 * check on_list without danger of it being re-added.
12965 */
12966 if (!tg->cfs_rq[cpu]->on_list)
12967 continue;
12968
12969 rq = cpu_rq(cpu);
12970
12971 raw_spin_rq_lock_irqsave(rq, flags);
12972 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
12973 raw_spin_rq_unlock_irqrestore(rq, flags);
12974 }
12975 }
12976
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)12977 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
12978 struct sched_entity *se, int cpu,
12979 struct sched_entity *parent)
12980 {
12981 struct rq *rq = cpu_rq(cpu);
12982
12983 cfs_rq->tg = tg;
12984 cfs_rq->rq = rq;
12985 init_cfs_rq_runtime(cfs_rq);
12986
12987 tg->cfs_rq[cpu] = cfs_rq;
12988 tg->se[cpu] = se;
12989
12990 /* se could be NULL for root_task_group */
12991 if (!se)
12992 return;
12993
12994 if (!parent) {
12995 se->cfs_rq = &rq->cfs;
12996 se->depth = 0;
12997 } else {
12998 se->cfs_rq = parent->my_q;
12999 se->depth = parent->depth + 1;
13000 }
13001
13002 se->my_q = cfs_rq;
13003 /* guarantee group entities always have weight */
13004 update_load_set(&se->load, NICE_0_LOAD);
13005 se->parent = parent;
13006 }
13007
13008 static DEFINE_MUTEX(shares_mutex);
13009
__sched_group_set_shares(struct task_group * tg,unsigned long shares)13010 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares)
13011 {
13012 int i;
13013
13014 lockdep_assert_held(&shares_mutex);
13015
13016 /*
13017 * We can't change the weight of the root cgroup.
13018 */
13019 if (!tg->se[0])
13020 return -EINVAL;
13021
13022 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
13023
13024 if (tg->shares == shares)
13025 return 0;
13026
13027 tg->shares = shares;
13028 for_each_possible_cpu(i) {
13029 struct rq *rq = cpu_rq(i);
13030 struct sched_entity *se = tg->se[i];
13031 struct rq_flags rf;
13032
13033 /* Propagate contribution to hierarchy */
13034 rq_lock_irqsave(rq, &rf);
13035 update_rq_clock(rq);
13036 for_each_sched_entity(se) {
13037 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
13038 update_cfs_group(se);
13039 }
13040 rq_unlock_irqrestore(rq, &rf);
13041 }
13042
13043 return 0;
13044 }
13045
sched_group_set_shares(struct task_group * tg,unsigned long shares)13046 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
13047 {
13048 int ret;
13049
13050 mutex_lock(&shares_mutex);
13051 if (tg_is_idle(tg))
13052 ret = -EINVAL;
13053 else
13054 ret = __sched_group_set_shares(tg, shares);
13055 mutex_unlock(&shares_mutex);
13056
13057 return ret;
13058 }
13059
sched_group_set_idle(struct task_group * tg,long idle)13060 int sched_group_set_idle(struct task_group *tg, long idle)
13061 {
13062 int i;
13063
13064 if (tg == &root_task_group)
13065 return -EINVAL;
13066
13067 if (idle < 0 || idle > 1)
13068 return -EINVAL;
13069
13070 mutex_lock(&shares_mutex);
13071
13072 if (tg->idle == idle) {
13073 mutex_unlock(&shares_mutex);
13074 return 0;
13075 }
13076
13077 tg->idle = idle;
13078
13079 for_each_possible_cpu(i) {
13080 struct rq *rq = cpu_rq(i);
13081 struct sched_entity *se = tg->se[i];
13082 struct cfs_rq *parent_cfs_rq, *grp_cfs_rq = tg->cfs_rq[i];
13083 bool was_idle = cfs_rq_is_idle(grp_cfs_rq);
13084 long idle_task_delta;
13085 struct rq_flags rf;
13086
13087 rq_lock_irqsave(rq, &rf);
13088
13089 grp_cfs_rq->idle = idle;
13090 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq)))
13091 goto next_cpu;
13092
13093 if (se->on_rq) {
13094 parent_cfs_rq = cfs_rq_of(se);
13095 if (cfs_rq_is_idle(grp_cfs_rq))
13096 parent_cfs_rq->idle_nr_running++;
13097 else
13098 parent_cfs_rq->idle_nr_running--;
13099 }
13100
13101 idle_task_delta = grp_cfs_rq->h_nr_running -
13102 grp_cfs_rq->idle_h_nr_running;
13103 if (!cfs_rq_is_idle(grp_cfs_rq))
13104 idle_task_delta *= -1;
13105
13106 for_each_sched_entity(se) {
13107 struct cfs_rq *cfs_rq = cfs_rq_of(se);
13108
13109 if (!se->on_rq)
13110 break;
13111
13112 cfs_rq->idle_h_nr_running += idle_task_delta;
13113
13114 /* Already accounted at parent level and above. */
13115 if (cfs_rq_is_idle(cfs_rq))
13116 break;
13117 }
13118
13119 next_cpu:
13120 rq_unlock_irqrestore(rq, &rf);
13121 }
13122
13123 /* Idle groups have minimum weight. */
13124 if (tg_is_idle(tg))
13125 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO));
13126 else
13127 __sched_group_set_shares(tg, NICE_0_LOAD);
13128
13129 mutex_unlock(&shares_mutex);
13130 return 0;
13131 }
13132
13133 #else /* CONFIG_FAIR_GROUP_SCHED */
13134
free_fair_sched_group(struct task_group * tg)13135 void free_fair_sched_group(struct task_group *tg) { }
13136
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)13137 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
13138 {
13139 return 1;
13140 }
13141
online_fair_sched_group(struct task_group * tg)13142 void online_fair_sched_group(struct task_group *tg) { }
13143
unregister_fair_sched_group(struct task_group * tg)13144 void unregister_fair_sched_group(struct task_group *tg) { }
13145
13146 #endif /* CONFIG_FAIR_GROUP_SCHED */
13147
13148
get_rr_interval_fair(struct rq * rq,struct task_struct * task)13149 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
13150 {
13151 struct sched_entity *se = &task->se;
13152 unsigned int rr_interval = 0;
13153
13154 /*
13155 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
13156 * idle runqueue:
13157 */
13158 if (rq->cfs.load.weight)
13159 rr_interval = NS_TO_JIFFIES(se->slice);
13160
13161 return rr_interval;
13162 }
13163
13164 /*
13165 * All the scheduling class methods:
13166 */
13167 DEFINE_SCHED_CLASS(fair) = {
13168
13169 .enqueue_task = enqueue_task_fair,
13170 .dequeue_task = dequeue_task_fair,
13171 .yield_task = yield_task_fair,
13172 .yield_to_task = yield_to_task_fair,
13173
13174 .check_preempt_curr = check_preempt_wakeup,
13175
13176 .pick_next_task = __pick_next_task_fair,
13177 .put_prev_task = put_prev_task_fair,
13178 .set_next_task = set_next_task_fair,
13179
13180 #ifdef CONFIG_SMP
13181 .balance = balance_fair,
13182 .pick_task = pick_task_fair,
13183 .select_task_rq = select_task_rq_fair,
13184 .migrate_task_rq = migrate_task_rq_fair,
13185
13186 .rq_online = rq_online_fair,
13187 .rq_offline = rq_offline_fair,
13188
13189 .task_dead = task_dead_fair,
13190 .set_cpus_allowed = set_cpus_allowed_common,
13191 #endif
13192
13193 .task_tick = task_tick_fair,
13194 .task_fork = task_fork_fair,
13195
13196 .prio_changed = prio_changed_fair,
13197 .switched_from = switched_from_fair,
13198 .switched_to = switched_to_fair,
13199
13200 .get_rr_interval = get_rr_interval_fair,
13201
13202 .update_curr = update_curr_fair,
13203
13204 #ifdef CONFIG_FAIR_GROUP_SCHED
13205 .task_change_group = task_change_group_fair,
13206 #endif
13207
13208 #ifdef CONFIG_SCHED_CORE
13209 .task_is_throttled = task_is_throttled_fair,
13210 #endif
13211
13212 #ifdef CONFIG_UCLAMP_TASK
13213 .uclamp_enabled = 1,
13214 #endif
13215 };
13216
13217 #ifdef CONFIG_SCHED_DEBUG
print_cfs_stats(struct seq_file * m,int cpu)13218 void print_cfs_stats(struct seq_file *m, int cpu)
13219 {
13220 struct cfs_rq *cfs_rq, *pos;
13221
13222 rcu_read_lock();
13223 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
13224 print_cfs_rq(m, cpu, cfs_rq);
13225 rcu_read_unlock();
13226 }
13227
13228 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)13229 void show_numa_stats(struct task_struct *p, struct seq_file *m)
13230 {
13231 int node;
13232 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
13233 struct numa_group *ng;
13234
13235 rcu_read_lock();
13236 ng = rcu_dereference(p->numa_group);
13237 for_each_online_node(node) {
13238 if (p->numa_faults) {
13239 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
13240 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
13241 }
13242 if (ng) {
13243 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
13244 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
13245 }
13246 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
13247 }
13248 rcu_read_unlock();
13249 }
13250 #endif /* CONFIG_NUMA_BALANCING */
13251 #endif /* CONFIG_SCHED_DEBUG */
13252
init_sched_fair_class(void)13253 __init void init_sched_fair_class(void)
13254 {
13255 #ifdef CONFIG_SMP
13256 int i;
13257
13258 for_each_possible_cpu(i) {
13259 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i));
13260 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i));
13261 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i),
13262 GFP_KERNEL, cpu_to_node(i));
13263
13264 #ifdef CONFIG_CFS_BANDWIDTH
13265 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i));
13266 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list);
13267 #endif
13268 }
13269
13270 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
13271
13272 #ifdef CONFIG_NO_HZ_COMMON
13273 nohz.next_balance = jiffies;
13274 nohz.next_blocked = jiffies;
13275 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
13276 #endif
13277 #endif /* SMP */
13278
13279 }
13280