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