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)3967 unsigned long uclamp_task_util(struct task_struct *p)
3968 #else
3969 static inline unsigned long uclamp_task_util(struct task_struct *p)
3970 #endif
3971 {
3972 return clamp(task_util_est(p),
3973 uclamp_eff_value(p, UCLAMP_MIN),
3974 uclamp_eff_value(p, UCLAMP_MAX));
3975 }
3976 #else
3977 #ifdef CONFIG_SCHED_RT_CAS
uclamp_task_util(struct task_struct * p)3978 unsigned long uclamp_task_util(struct task_struct *p)
3979 #else
3980 static inline unsigned long uclamp_task_util(struct task_struct *p)
3981 #endif
3982 {
3983 return task_util_est(p);
3984 }
3985 #endif
3986
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)3987 static inline void util_est_enqueue(struct cfs_rq *cfs_rq,
3988 struct task_struct *p)
3989 {
3990 unsigned int enqueued;
3991
3992 if (!sched_feat(UTIL_EST))
3993 return;
3994
3995 /* Update root cfs_rq's estimated utilization */
3996 enqueued = cfs_rq->avg.util_est.enqueued;
3997 enqueued += _task_util_est(p);
3998 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
3999
4000 trace_sched_util_est_cfs_tp(cfs_rq);
4001 }
4002
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4003 static inline void util_est_dequeue(struct cfs_rq *cfs_rq,
4004 struct task_struct *p)
4005 {
4006 unsigned int enqueued;
4007
4008 if (!sched_feat(UTIL_EST))
4009 return;
4010
4011 /* Update root cfs_rq's estimated utilization */
4012 enqueued = cfs_rq->avg.util_est.enqueued;
4013 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p));
4014 WRITE_ONCE(cfs_rq->avg.util_est.enqueued, enqueued);
4015
4016 trace_sched_util_est_cfs_tp(cfs_rq);
4017 }
4018
4019 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100)
4020
4021 /*
4022 * Check if a (signed) value is within a specified (unsigned) margin,
4023 * based on the observation that:
4024 *
4025 * abs(x) < y := (unsigned)(x + y - 1) < (2 * y - 1)
4026 *
4027 * NOTE: this only works when value + maring < INT_MAX.
4028 */
within_margin(int value,int margin)4029 static inline bool within_margin(int value, int margin)
4030 {
4031 return ((unsigned int)(value + margin - 1) < (2 * margin - 1));
4032 }
4033
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4034 static inline void util_est_update(struct cfs_rq *cfs_rq,
4035 struct task_struct *p,
4036 bool task_sleep)
4037 {
4038 long last_ewma_diff, last_enqueued_diff;
4039 struct util_est ue;
4040
4041 if (!sched_feat(UTIL_EST))
4042 return;
4043
4044 /*
4045 * Skip update of task's estimated utilization when the task has not
4046 * yet completed an activation, e.g. being migrated.
4047 */
4048 if (!task_sleep)
4049 return;
4050
4051 /*
4052 * If the PELT values haven't changed since enqueue time,
4053 * skip the util_est update.
4054 */
4055 ue = p->se.avg.util_est;
4056 if (ue.enqueued & UTIL_AVG_UNCHANGED)
4057 return;
4058
4059 last_enqueued_diff = ue.enqueued;
4060
4061 /*
4062 * Reset EWMA on utilization increases, the moving average is used only
4063 * to smooth utilization decreases.
4064 */
4065 ue.enqueued = task_util(p);
4066 if (sched_feat(UTIL_EST_FASTUP)) {
4067 if (ue.ewma < ue.enqueued) {
4068 ue.ewma = ue.enqueued;
4069 goto done;
4070 }
4071 }
4072
4073 /*
4074 * Skip update of task's estimated utilization when its members are
4075 * already ~1% close to its last activation value.
4076 */
4077 last_ewma_diff = ue.enqueued - ue.ewma;
4078 last_enqueued_diff -= ue.enqueued;
4079 if (within_margin(last_ewma_diff, UTIL_EST_MARGIN)) {
4080 if (!within_margin(last_enqueued_diff, UTIL_EST_MARGIN))
4081 goto done;
4082
4083 return;
4084 }
4085
4086 /*
4087 * To avoid overestimation of actual task utilization, skip updates if
4088 * we cannot grant there is idle time in this CPU.
4089 */
4090 if (task_util(p) > capacity_orig_of(cpu_of(rq_of(cfs_rq))))
4091 return;
4092
4093 /*
4094 * Update Task's estimated utilization
4095 *
4096 * When *p completes an activation we can consolidate another sample
4097 * of the task size. This is done by storing the current PELT value
4098 * as ue.enqueued and by using this value to update the Exponential
4099 * Weighted Moving Average (EWMA):
4100 *
4101 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1)
4102 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1)
4103 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1)
4104 * = w * ( last_ewma_diff ) + ewma(t-1)
4105 * = w * (last_ewma_diff + ewma(t-1) / w)
4106 *
4107 * Where 'w' is the weight of new samples, which is configured to be
4108 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT)
4109 */
4110 ue.ewma <<= UTIL_EST_WEIGHT_SHIFT;
4111 ue.ewma += last_ewma_diff;
4112 ue.ewma >>= UTIL_EST_WEIGHT_SHIFT;
4113 done:
4114 ue.enqueued |= UTIL_AVG_UNCHANGED;
4115 WRITE_ONCE(p->se.avg.util_est, ue);
4116
4117 trace_sched_util_est_se_tp(&p->se);
4118 }
4119
util_fits_cpu(unsigned long util,unsigned long uclamp_min,unsigned long uclamp_max,int cpu)4120 static inline int util_fits_cpu(unsigned long util,
4121 unsigned long uclamp_min,
4122 unsigned long uclamp_max,
4123 int cpu)
4124 {
4125 unsigned long capacity_orig, capacity_orig_thermal;
4126 unsigned long capacity = capacity_of(cpu);
4127 bool fits, uclamp_max_fits;
4128
4129 /*
4130 * Check if the real util fits without any uclamp boost/cap applied.
4131 */
4132 fits = fits_capacity(util, capacity);
4133
4134 if (!uclamp_is_used())
4135 return fits;
4136
4137 /*
4138 * We must use capacity_orig_of() for comparing against uclamp_min and
4139 * uclamp_max. We only care about capacity pressure (by using
4140 * capacity_of()) for comparing against the real util.
4141 *
4142 * If a task is boosted to 1024 for example, we don't want a tiny
4143 * pressure to skew the check whether it fits a CPU or not.
4144 *
4145 * Similarly if a task is capped to capacity_orig_of(little_cpu), it
4146 * should fit a little cpu even if there's some pressure.
4147 *
4148 * Only exception is for thermal pressure since it has a direct impact
4149 * on available OPP of the system.
4150 *
4151 * We honour it for uclamp_min only as a drop in performance level
4152 * could result in not getting the requested minimum performance level.
4153 *
4154 * For uclamp_max, we can tolerate a drop in performance level as the
4155 * goal is to cap the task. So it's okay if it's getting less.
4156 *
4157 * In case of capacity inversion, which is not handled yet, we should
4158 * honour the inverted capacity for both uclamp_min and uclamp_max all
4159 * the time.
4160 */
4161 capacity_orig = capacity_orig_of(cpu);
4162 capacity_orig_thermal = capacity_orig - arch_scale_thermal_pressure(cpu);
4163
4164 /*
4165 * We want to force a task to fit a cpu as implied by uclamp_max.
4166 * But we do have some corner cases to cater for..
4167 *
4168 *
4169 * C=z
4170 * | ___
4171 * | C=y | |
4172 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4173 * | C=x | | | |
4174 * | ___ | | | |
4175 * | | | | | | | (util somewhere in this region)
4176 * | | | | | | |
4177 * | | | | | | |
4178 * +----------------------------------------
4179 * cpu0 cpu1 cpu2
4180 *
4181 * In the above example if a task is capped to a specific performance
4182 * point, y, then when:
4183 *
4184 * * util = 80% of x then it does not fit on cpu0 and should migrate
4185 * to cpu1
4186 * * util = 80% of y then it is forced to fit on cpu1 to honour
4187 * uclamp_max request.
4188 *
4189 * which is what we're enforcing here. A task always fits if
4190 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig,
4191 * the normal upmigration rules should withhold still.
4192 *
4193 * Only exception is when we are on max capacity, then we need to be
4194 * careful not to block overutilized state. This is so because:
4195 *
4196 * 1. There's no concept of capping at max_capacity! We can't go
4197 * beyond this performance level anyway.
4198 * 2. The system is being saturated when we're operating near
4199 * max capacity, it doesn't make sense to block overutilized.
4200 */
4201 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE);
4202 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig);
4203 fits = fits || uclamp_max_fits;
4204
4205 /*
4206 *
4207 * C=z
4208 * | ___ (region a, capped, util >= uclamp_max)
4209 * | C=y | |
4210 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max
4211 * | C=x | | | |
4212 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max)
4213 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min
4214 * | | | | | | |
4215 * | | | | | | | (region c, boosted, util < uclamp_min)
4216 * +----------------------------------------
4217 * cpu0 cpu1 cpu2
4218 *
4219 * a) If util > uclamp_max, then we're capped, we don't care about
4220 * actual fitness value here. We only care if uclamp_max fits
4221 * capacity without taking margin/pressure into account.
4222 * See comment above.
4223 *
4224 * b) If uclamp_min <= util <= uclamp_max, then the normal
4225 * fits_capacity() rules apply. Except we need to ensure that we
4226 * enforce we remain within uclamp_max, see comment above.
4227 *
4228 * c) If util < uclamp_min, then we are boosted. Same as (b) but we
4229 * need to take into account the boosted value fits the CPU without
4230 * taking margin/pressure into account.
4231 *
4232 * Cases (a) and (b) are handled in the 'fits' variable already. We
4233 * just need to consider an extra check for case (c) after ensuring we
4234 * handle the case uclamp_min > uclamp_max.
4235 */
4236 uclamp_min = min(uclamp_min, uclamp_max);
4237 if (util < uclamp_min && capacity_orig != SCHED_CAPACITY_SCALE)
4238 fits = fits && (uclamp_min <= capacity_orig_thermal);
4239
4240 return fits;
4241 }
4242
task_fits_capacity(struct task_struct * p,unsigned long capacity)4243 static inline int task_fits_capacity(struct task_struct *p,
4244 unsigned long capacity)
4245 {
4246 return fits_capacity(uclamp_task_util(p), capacity);
4247 }
4248
4249 #ifdef CONFIG_SCHED_RTG
task_fits_max(struct task_struct * p,int cpu)4250 bool task_fits_max(struct task_struct *p, int cpu)
4251 {
4252 unsigned long capacity = capacity_orig_of(cpu);
4253 unsigned long max_capacity = cpu_rq(cpu)->rd->max_cpu_capacity;
4254
4255 if (capacity == max_capacity)
4256 return true;
4257
4258 return task_fits_capacity(p, capacity);
4259 }
4260 #endif
4261
update_misfit_status(struct task_struct * p,struct rq * rq)4262 static inline void update_misfit_status(struct task_struct *p, struct rq *rq)
4263 {
4264 bool task_fits = false;
4265 #ifdef CONFIG_SCHED_RTG
4266 int cpu = cpu_of(rq);
4267 struct cpumask *rtg_target = NULL;
4268 #endif
4269
4270 if (!static_branch_unlikely(&sched_asym_cpucapacity))
4271 return;
4272
4273 if (!p || p->nr_cpus_allowed == 1) {
4274 rq->misfit_task_load = 0;
4275 return;
4276 }
4277
4278 #ifdef CONFIG_SCHED_RTG
4279 rtg_target = find_rtg_target(p);
4280 if (rtg_target)
4281 task_fits = capacity_orig_of(cpu) >=
4282 capacity_orig_of(cpumask_first(rtg_target));
4283 else
4284 task_fits = task_fits_capacity(p, capacity_of(cpu_of(rq)));
4285 #else
4286 task_fits = task_fits_capacity(p, capacity_of(cpu_of(rq)));
4287 #endif
4288 if (task_fits) {
4289 rq->misfit_task_load = 0;
4290 return;
4291 }
4292
4293 /*
4294 * Make sure that misfit_task_load will not be null even if
4295 * task_h_load() returns 0.
4296 */
4297 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1);
4298 }
4299
4300 #else /* CONFIG_SMP */
4301
4302 #define UPDATE_TG 0x0
4303 #define SKIP_AGE_LOAD 0x0
4304 #define DO_ATTACH 0x0
4305
update_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se,int not_used1)4306 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int not_used1)
4307 {
4308 cfs_rq_util_change(cfs_rq, 0);
4309 }
4310
remove_entity_load_avg(struct sched_entity * se)4311 static inline void remove_entity_load_avg(struct sched_entity *se) {}
4312
4313 static inline void
attach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4314 attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4315 static inline void
detach_entity_load_avg(struct cfs_rq * cfs_rq,struct sched_entity * se)4316 detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) {}
4317
newidle_balance(struct rq * rq,struct rq_flags * rf)4318 static inline int newidle_balance(struct rq *rq, struct rq_flags *rf)
4319 {
4320 return 0;
4321 }
4322
4323 static inline void
util_est_enqueue(struct cfs_rq * cfs_rq,struct task_struct * p)4324 util_est_enqueue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4325
4326 static inline void
util_est_dequeue(struct cfs_rq * cfs_rq,struct task_struct * p)4327 util_est_dequeue(struct cfs_rq *cfs_rq, struct task_struct *p) {}
4328
4329 static inline void
util_est_update(struct cfs_rq * cfs_rq,struct task_struct * p,bool task_sleep)4330 util_est_update(struct cfs_rq *cfs_rq, struct task_struct *p,
4331 bool task_sleep) {}
update_misfit_status(struct task_struct * p,struct rq * rq)4332 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) {}
4333
4334 #endif /* CONFIG_SMP */
4335
check_spread(struct cfs_rq * cfs_rq,struct sched_entity * se)4336 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
4337 {
4338 #ifdef CONFIG_SCHED_DEBUG
4339 s64 d = se->vruntime - cfs_rq->min_vruntime;
4340
4341 if (d < 0)
4342 d = -d;
4343
4344 if (d > 3*sysctl_sched_latency)
4345 schedstat_inc(cfs_rq->nr_spread_over);
4346 #endif
4347 }
4348
4349 static void
place_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int initial)4350 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
4351 {
4352 u64 vruntime = cfs_rq->min_vruntime;
4353
4354 /*
4355 * The 'current' period is already promised to the current tasks,
4356 * however the extra weight of the new task will slow them down a
4357 * little, place the new task so that it fits in the slot that
4358 * stays open at the end.
4359 */
4360 if (initial && sched_feat(START_DEBIT))
4361 vruntime += sched_vslice(cfs_rq, se);
4362
4363 /* sleeps up to a single latency don't count. */
4364 if (!initial) {
4365 unsigned long thresh = sysctl_sched_latency;
4366
4367 /*
4368 * Halve their sleep time's effect, to allow
4369 * for a gentler effect of sleepers:
4370 */
4371 if (sched_feat(GENTLE_FAIR_SLEEPERS))
4372 thresh >>= 1;
4373
4374 vruntime -= thresh;
4375 }
4376
4377 /* ensure we never gain time by being placed backwards. */
4378 se->vruntime = max_vruntime(se->vruntime, vruntime);
4379 }
4380
4381 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
4382
check_schedstat_required(void)4383 static inline void check_schedstat_required(void)
4384 {
4385 #ifdef CONFIG_SCHEDSTATS
4386 if (schedstat_enabled())
4387 return;
4388
4389 /* Force schedstat enabled if a dependent tracepoint is active */
4390 if (trace_sched_stat_wait_enabled() ||
4391 trace_sched_stat_sleep_enabled() ||
4392 trace_sched_stat_iowait_enabled() ||
4393 trace_sched_stat_blocked_enabled() ||
4394 trace_sched_stat_runtime_enabled()) {
4395 printk_deferred_once("Scheduler tracepoints stat_sleep, stat_iowait, "
4396 "stat_blocked and stat_runtime require the "
4397 "kernel parameter schedstats=enable or "
4398 "kernel.sched_schedstats=1\n");
4399 }
4400 #endif
4401 }
4402
4403 static inline bool cfs_bandwidth_used(void);
4404
4405 /*
4406 * MIGRATION
4407 *
4408 * dequeue
4409 * update_curr()
4410 * update_min_vruntime()
4411 * vruntime -= min_vruntime
4412 *
4413 * enqueue
4414 * update_curr()
4415 * update_min_vruntime()
4416 * vruntime += min_vruntime
4417 *
4418 * this way the vruntime transition between RQs is done when both
4419 * min_vruntime are up-to-date.
4420 *
4421 * WAKEUP (remote)
4422 *
4423 * ->migrate_task_rq_fair() (p->state == TASK_WAKING)
4424 * vruntime -= min_vruntime
4425 *
4426 * enqueue
4427 * update_curr()
4428 * update_min_vruntime()
4429 * vruntime += min_vruntime
4430 *
4431 * this way we don't have the most up-to-date min_vruntime on the originating
4432 * CPU and an up-to-date min_vruntime on the destination CPU.
4433 */
4434
4435 static void
enqueue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4436 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4437 {
4438 bool renorm = !(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_MIGRATED);
4439 bool curr = cfs_rq->curr == se;
4440
4441 /*
4442 * If we're the current task, we must renormalise before calling
4443 * update_curr().
4444 */
4445 if (renorm && curr)
4446 se->vruntime += cfs_rq->min_vruntime;
4447
4448 update_curr(cfs_rq);
4449
4450 /*
4451 * Otherwise, renormalise after, such that we're placed at the current
4452 * moment in time, instead of some random moment in the past. Being
4453 * placed in the past could significantly boost this task to the
4454 * fairness detriment of existing tasks.
4455 */
4456 if (renorm && !curr)
4457 se->vruntime += cfs_rq->min_vruntime;
4458
4459 /*
4460 * When enqueuing a sched_entity, we must:
4461 * - Update loads to have both entity and cfs_rq synced with now.
4462 * - Add its load to cfs_rq->runnable_avg
4463 * - For group_entity, update its weight to reflect the new share of
4464 * its group cfs_rq
4465 * - Add its new weight to cfs_rq->load.weight
4466 */
4467 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH);
4468 se_update_runnable(se);
4469 update_cfs_group(se);
4470 account_entity_enqueue(cfs_rq, se);
4471
4472 if (flags & ENQUEUE_WAKEUP)
4473 place_entity(cfs_rq, se, 0);
4474
4475 check_schedstat_required();
4476 update_stats_enqueue(cfs_rq, se, flags);
4477 check_spread(cfs_rq, se);
4478 if (!curr)
4479 __enqueue_entity(cfs_rq, se);
4480 se->on_rq = 1;
4481
4482 /*
4483 * When bandwidth control is enabled, cfs might have been removed
4484 * because of a parent been throttled but cfs->nr_running > 1. Try to
4485 * add it unconditionnally.
4486 */
4487 if (cfs_rq->nr_running == 1 || cfs_bandwidth_used())
4488 list_add_leaf_cfs_rq(cfs_rq);
4489
4490 if (cfs_rq->nr_running == 1)
4491 check_enqueue_throttle(cfs_rq);
4492 }
4493
__clear_buddies_last(struct sched_entity * se)4494 static void __clear_buddies_last(struct sched_entity *se)
4495 {
4496 for_each_sched_entity(se) {
4497 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4498 if (cfs_rq->last != se)
4499 break;
4500
4501 cfs_rq->last = NULL;
4502 }
4503 }
4504
__clear_buddies_next(struct sched_entity * se)4505 static void __clear_buddies_next(struct sched_entity *se)
4506 {
4507 for_each_sched_entity(se) {
4508 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4509 if (cfs_rq->next != se)
4510 break;
4511
4512 cfs_rq->next = NULL;
4513 }
4514 }
4515
__clear_buddies_skip(struct sched_entity * se)4516 static void __clear_buddies_skip(struct sched_entity *se)
4517 {
4518 for_each_sched_entity(se) {
4519 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4520 if (cfs_rq->skip != se)
4521 break;
4522
4523 cfs_rq->skip = NULL;
4524 }
4525 }
4526
clear_buddies(struct cfs_rq * cfs_rq,struct sched_entity * se)4527 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
4528 {
4529 if (cfs_rq->last == se)
4530 __clear_buddies_last(se);
4531
4532 if (cfs_rq->next == se)
4533 __clear_buddies_next(se);
4534
4535 if (cfs_rq->skip == se)
4536 __clear_buddies_skip(se);
4537 }
4538
4539 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4540
4541 static void
dequeue_entity(struct cfs_rq * cfs_rq,struct sched_entity * se,int flags)4542 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
4543 {
4544 /*
4545 * Update run-time statistics of the 'current'.
4546 */
4547 update_curr(cfs_rq);
4548
4549 /*
4550 * When dequeuing a sched_entity, we must:
4551 * - Update loads to have both entity and cfs_rq synced with now.
4552 * - Subtract its load from the cfs_rq->runnable_avg.
4553 * - Subtract its previous weight from cfs_rq->load.weight.
4554 * - For group entity, update its weight to reflect the new share
4555 * of its group cfs_rq.
4556 */
4557 update_load_avg(cfs_rq, se, UPDATE_TG);
4558 se_update_runnable(se);
4559
4560 update_stats_dequeue(cfs_rq, se, flags);
4561
4562 clear_buddies(cfs_rq, se);
4563
4564 if (se != cfs_rq->curr)
4565 __dequeue_entity(cfs_rq, se);
4566 se->on_rq = 0;
4567 account_entity_dequeue(cfs_rq, se);
4568
4569 /*
4570 * Normalize after update_curr(); which will also have moved
4571 * min_vruntime if @se is the one holding it back. But before doing
4572 * update_min_vruntime() again, which will discount @se's position and
4573 * can move min_vruntime forward still more.
4574 */
4575 if (!(flags & DEQUEUE_SLEEP))
4576 se->vruntime -= cfs_rq->min_vruntime;
4577
4578 /* return excess runtime on last dequeue */
4579 return_cfs_rq_runtime(cfs_rq);
4580
4581 update_cfs_group(se);
4582
4583 /*
4584 * Now advance min_vruntime if @se was the entity holding it back,
4585 * except when: DEQUEUE_SAVE && !DEQUEUE_MOVE, in this case we'll be
4586 * put back on, and if we advance min_vruntime, we'll be placed back
4587 * further than we started -- ie. we'll be penalized.
4588 */
4589 if ((flags & (DEQUEUE_SAVE | DEQUEUE_MOVE)) != DEQUEUE_SAVE)
4590 update_min_vruntime(cfs_rq);
4591 }
4592
4593 /*
4594 * Preempt the current task with a newly woken task if needed:
4595 */
4596 static void
check_preempt_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr)4597 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4598 {
4599 unsigned long ideal_runtime, delta_exec;
4600 struct sched_entity *se;
4601 s64 delta;
4602
4603 ideal_runtime = sched_slice(cfs_rq, curr);
4604 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
4605 if (delta_exec > ideal_runtime) {
4606 resched_curr(rq_of(cfs_rq));
4607 /*
4608 * The current task ran long enough, ensure it doesn't get
4609 * re-elected due to buddy favours.
4610 */
4611 clear_buddies(cfs_rq, curr);
4612 return;
4613 }
4614
4615 /*
4616 * Ensure that a task that missed wakeup preemption by a
4617 * narrow margin doesn't have to wait for a full slice.
4618 * This also mitigates buddy induced latencies under load.
4619 */
4620 if (delta_exec < sysctl_sched_min_granularity)
4621 return;
4622
4623 se = __pick_first_entity(cfs_rq);
4624 delta = curr->vruntime - se->vruntime;
4625
4626 if (delta < 0)
4627 return;
4628
4629 if (delta > ideal_runtime)
4630 resched_curr(rq_of(cfs_rq));
4631 }
4632
4633 static void
set_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * se)4634 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
4635 {
4636 /* 'current' is not kept within the tree. */
4637 if (se->on_rq) {
4638 /*
4639 * Any task has to be enqueued before it get to execute on
4640 * a CPU. So account for the time it spent waiting on the
4641 * runqueue.
4642 */
4643 update_stats_wait_end(cfs_rq, se);
4644 __dequeue_entity(cfs_rq, se);
4645 update_load_avg(cfs_rq, se, UPDATE_TG);
4646 }
4647
4648 update_stats_curr_start(cfs_rq, se);
4649 cfs_rq->curr = se;
4650
4651 /*
4652 * Track our maximum slice length, if the CPU's load is at
4653 * least twice that of our own weight (i.e. dont track it
4654 * when there are only lesser-weight tasks around):
4655 */
4656 if (schedstat_enabled() &&
4657 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) {
4658 schedstat_set(se->statistics.slice_max,
4659 max((u64)schedstat_val(se->statistics.slice_max),
4660 se->sum_exec_runtime - se->prev_sum_exec_runtime));
4661 }
4662
4663 se->prev_sum_exec_runtime = se->sum_exec_runtime;
4664 }
4665
4666 static int
4667 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
4668
4669 /*
4670 * Pick the next process, keeping these things in mind, in this order:
4671 * 1) keep things fair between processes/task groups
4672 * 2) pick the "next" process, since someone really wants that to run
4673 * 3) pick the "last" process, for cache locality
4674 * 4) do not run the "skip" process, if something else is available
4675 */
4676 static struct sched_entity *
pick_next_entity(struct cfs_rq * cfs_rq,struct sched_entity * curr)4677 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
4678 {
4679 struct sched_entity *left = __pick_first_entity(cfs_rq);
4680 struct sched_entity *se;
4681
4682 /*
4683 * If curr is set we have to see if its left of the leftmost entity
4684 * still in the tree, provided there was anything in the tree at all.
4685 */
4686 if (!left || (curr && entity_before(curr, left)))
4687 left = curr;
4688
4689 se = left; /* ideally we run the leftmost entity */
4690
4691 /*
4692 * Avoid running the skip buddy, if running something else can
4693 * be done without getting too unfair.
4694 */
4695 if (cfs_rq->skip == se) {
4696 struct sched_entity *second;
4697
4698 if (se == curr) {
4699 second = __pick_first_entity(cfs_rq);
4700 } else {
4701 second = __pick_next_entity(se);
4702 if (!second || (curr && entity_before(curr, second)))
4703 second = curr;
4704 }
4705
4706 if (second && wakeup_preempt_entity(second, left) < 1)
4707 se = second;
4708 }
4709
4710 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) {
4711 /*
4712 * Someone really wants this to run. If it's not unfair, run it.
4713 */
4714 se = cfs_rq->next;
4715 } else if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) {
4716 /*
4717 * Prefer last buddy, try to return the CPU to a preempted task.
4718 */
4719 se = cfs_rq->last;
4720 }
4721
4722 clear_buddies(cfs_rq, se);
4723
4724 return se;
4725 }
4726
4727 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
4728
put_prev_entity(struct cfs_rq * cfs_rq,struct sched_entity * prev)4729 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
4730 {
4731 /*
4732 * If still on the runqueue then deactivate_task()
4733 * was not called and update_curr() has to be done:
4734 */
4735 if (prev->on_rq)
4736 update_curr(cfs_rq);
4737
4738 /* throttle cfs_rqs exceeding runtime */
4739 check_cfs_rq_runtime(cfs_rq);
4740
4741 check_spread(cfs_rq, prev);
4742
4743 if (prev->on_rq) {
4744 update_stats_wait_start(cfs_rq, prev);
4745 /* Put 'current' back into the tree. */
4746 __enqueue_entity(cfs_rq, prev);
4747 /* in !on_rq case, update occurred at dequeue */
4748 update_load_avg(cfs_rq, prev, 0);
4749 }
4750 cfs_rq->curr = NULL;
4751 }
4752
4753 static void
entity_tick(struct cfs_rq * cfs_rq,struct sched_entity * curr,int queued)4754 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
4755 {
4756 /*
4757 * Update run-time statistics of the 'current'.
4758 */
4759 update_curr(cfs_rq);
4760
4761 /*
4762 * Ensure that runnable average is periodically updated.
4763 */
4764 update_load_avg(cfs_rq, curr, UPDATE_TG);
4765 update_cfs_group(curr);
4766
4767 #ifdef CONFIG_SCHED_HRTICK
4768 /*
4769 * queued ticks are scheduled to match the slice, so don't bother
4770 * validating it and just reschedule.
4771 */
4772 if (queued) {
4773 resched_curr(rq_of(cfs_rq));
4774 return;
4775 }
4776 /*
4777 * don't let the period tick interfere with the hrtick preemption
4778 */
4779 if (!sched_feat(DOUBLE_TICK) &&
4780 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
4781 return;
4782 #endif
4783
4784 if (cfs_rq->nr_running > 1)
4785 check_preempt_tick(cfs_rq, curr);
4786 }
4787
4788
4789 /**************************************************
4790 * CFS bandwidth control machinery
4791 */
4792
4793 #ifdef CONFIG_CFS_BANDWIDTH
4794
4795 #ifdef CONFIG_JUMP_LABEL
4796 static struct static_key __cfs_bandwidth_used;
4797
cfs_bandwidth_used(void)4798 static inline bool cfs_bandwidth_used(void)
4799 {
4800 return static_key_false(&__cfs_bandwidth_used);
4801 }
4802
cfs_bandwidth_usage_inc(void)4803 void cfs_bandwidth_usage_inc(void)
4804 {
4805 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used);
4806 }
4807
cfs_bandwidth_usage_dec(void)4808 void cfs_bandwidth_usage_dec(void)
4809 {
4810 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used);
4811 }
4812 #else /* CONFIG_JUMP_LABEL */
cfs_bandwidth_used(void)4813 static bool cfs_bandwidth_used(void)
4814 {
4815 return true;
4816 }
4817
cfs_bandwidth_usage_inc(void)4818 void cfs_bandwidth_usage_inc(void) {}
cfs_bandwidth_usage_dec(void)4819 void cfs_bandwidth_usage_dec(void) {}
4820 #endif /* CONFIG_JUMP_LABEL */
4821
4822 /*
4823 * default period for cfs group bandwidth.
4824 * default: 0.1s, units: nanoseconds
4825 */
default_cfs_period(void)4826 static inline u64 default_cfs_period(void)
4827 {
4828 return 100000000ULL;
4829 }
4830
sched_cfs_bandwidth_slice(void)4831 static inline u64 sched_cfs_bandwidth_slice(void)
4832 {
4833 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
4834 }
4835
4836 /*
4837 * Replenish runtime according to assigned quota. We use sched_clock_cpu
4838 * directly instead of rq->clock to avoid adding additional synchronization
4839 * around rq->lock.
4840 *
4841 * requires cfs_b->lock
4842 */
__refill_cfs_bandwidth_runtime(struct cfs_bandwidth * cfs_b)4843 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
4844 {
4845 if (cfs_b->quota != RUNTIME_INF)
4846 cfs_b->runtime = cfs_b->quota;
4847 }
4848
tg_cfs_bandwidth(struct task_group * tg)4849 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4850 {
4851 return &tg->cfs_bandwidth;
4852 }
4853
4854 /* returns 0 on failure to allocate runtime */
__assign_cfs_rq_runtime(struct cfs_bandwidth * cfs_b,struct cfs_rq * cfs_rq,u64 target_runtime)4855 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b,
4856 struct cfs_rq *cfs_rq, u64 target_runtime)
4857 {
4858 u64 min_amount, amount = 0;
4859
4860 lockdep_assert_held(&cfs_b->lock);
4861
4862 /* note: this is a positive sum as runtime_remaining <= 0 */
4863 min_amount = target_runtime - cfs_rq->runtime_remaining;
4864
4865 if (cfs_b->quota == RUNTIME_INF)
4866 amount = min_amount;
4867 else {
4868 start_cfs_bandwidth(cfs_b);
4869
4870 if (cfs_b->runtime > 0) {
4871 amount = min(cfs_b->runtime, min_amount);
4872 cfs_b->runtime -= amount;
4873 cfs_b->idle = 0;
4874 }
4875 }
4876
4877 cfs_rq->runtime_remaining += amount;
4878
4879 return cfs_rq->runtime_remaining > 0;
4880 }
4881
4882 /* returns 0 on failure to allocate runtime */
assign_cfs_rq_runtime(struct cfs_rq * cfs_rq)4883 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
4884 {
4885 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4886 int ret;
4887
4888 raw_spin_lock(&cfs_b->lock);
4889 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice());
4890 raw_spin_unlock(&cfs_b->lock);
4891
4892 return ret;
4893 }
4894
__account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)4895 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4896 {
4897 /* dock delta_exec before expiring quota (as it could span periods) */
4898 cfs_rq->runtime_remaining -= delta_exec;
4899
4900 if (likely(cfs_rq->runtime_remaining > 0))
4901 return;
4902
4903 if (cfs_rq->throttled)
4904 return;
4905 /*
4906 * if we're unable to extend our runtime we resched so that the active
4907 * hierarchy can be throttled
4908 */
4909 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
4910 resched_curr(rq_of(cfs_rq));
4911 }
4912
4913 static __always_inline
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)4914 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
4915 {
4916 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
4917 return;
4918
4919 __account_cfs_rq_runtime(cfs_rq, delta_exec);
4920 }
4921
cfs_rq_throttled(struct cfs_rq * cfs_rq)4922 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4923 {
4924 return cfs_bandwidth_used() && cfs_rq->throttled;
4925 }
4926
4927 /* check whether cfs_rq, or any parent, is throttled */
throttled_hierarchy(struct cfs_rq * cfs_rq)4928 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4929 {
4930 return cfs_bandwidth_used() && cfs_rq->throttle_count;
4931 }
4932
4933 /*
4934 * Ensure that neither of the group entities corresponding to src_cpu or
4935 * dest_cpu are members of a throttled hierarchy when performing group
4936 * load-balance operations.
4937 */
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)4938 static inline int throttled_lb_pair(struct task_group *tg,
4939 int src_cpu, int dest_cpu)
4940 {
4941 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
4942
4943 src_cfs_rq = tg->cfs_rq[src_cpu];
4944 dest_cfs_rq = tg->cfs_rq[dest_cpu];
4945
4946 return throttled_hierarchy(src_cfs_rq) ||
4947 throttled_hierarchy(dest_cfs_rq);
4948 }
4949
tg_unthrottle_up(struct task_group * tg,void * data)4950 static int tg_unthrottle_up(struct task_group *tg, void *data)
4951 {
4952 struct rq *rq = data;
4953 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4954
4955 cfs_rq->throttle_count--;
4956 if (!cfs_rq->throttle_count) {
4957 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) -
4958 cfs_rq->throttled_clock_pelt;
4959
4960 /* Add cfs_rq with already running entity in the list */
4961 if (cfs_rq->nr_running >= 1)
4962 list_add_leaf_cfs_rq(cfs_rq);
4963 }
4964
4965 return 0;
4966 }
4967
tg_throttle_down(struct task_group * tg,void * data)4968 static int tg_throttle_down(struct task_group *tg, void *data)
4969 {
4970 struct rq *rq = data;
4971 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
4972
4973 /* group is entering throttled state, stop time */
4974 if (!cfs_rq->throttle_count) {
4975 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq);
4976 list_del_leaf_cfs_rq(cfs_rq);
4977 }
4978 cfs_rq->throttle_count++;
4979
4980 return 0;
4981 }
4982
throttle_cfs_rq(struct cfs_rq * cfs_rq)4983 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq)
4984 {
4985 struct rq *rq = rq_of(cfs_rq);
4986 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
4987 struct sched_entity *se;
4988 long task_delta, idle_task_delta, dequeue = 1;
4989
4990 raw_spin_lock(&cfs_b->lock);
4991 /* This will start the period timer if necessary */
4992 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) {
4993 /*
4994 * We have raced with bandwidth becoming available, and if we
4995 * actually throttled the timer might not unthrottle us for an
4996 * entire period. We additionally needed to make sure that any
4997 * subsequent check_cfs_rq_runtime calls agree not to throttle
4998 * us, as we may commit to do cfs put_prev+pick_next, so we ask
4999 * for 1ns of runtime rather than just check cfs_b.
5000 */
5001 dequeue = 0;
5002 } else {
5003 list_add_tail_rcu(&cfs_rq->throttled_list,
5004 &cfs_b->throttled_cfs_rq);
5005 }
5006 raw_spin_unlock(&cfs_b->lock);
5007
5008 if (!dequeue)
5009 return false; /* Throttle no longer required. */
5010
5011 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
5012
5013 /* freeze hierarchy runnable averages while throttled */
5014 rcu_read_lock();
5015 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
5016 rcu_read_unlock();
5017
5018 task_delta = cfs_rq->h_nr_running;
5019 idle_task_delta = cfs_rq->idle_h_nr_running;
5020 for_each_sched_entity(se) {
5021 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
5022 /* throttled entity or throttle-on-deactivate */
5023 if (!se->on_rq)
5024 break;
5025
5026 if (dequeue) {
5027 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
5028 } else {
5029 update_load_avg(qcfs_rq, se, 0);
5030 se_update_runnable(se);
5031 }
5032
5033 qcfs_rq->h_nr_running -= task_delta;
5034 qcfs_rq->idle_h_nr_running -= idle_task_delta;
5035 walt_dec_throttled_cfs_rq_stats(&qcfs_rq->walt_stats, cfs_rq);
5036
5037 if (qcfs_rq->load.weight)
5038 dequeue = 0;
5039 }
5040
5041 if (!se) {
5042 sub_nr_running(rq, task_delta);
5043 walt_dec_throttled_cfs_rq_stats(&rq->walt_stats, cfs_rq);
5044 }
5045
5046 /*
5047 * Note: distribution will already see us throttled via the
5048 * throttled-list. rq->lock protects completion.
5049 */
5050 cfs_rq->throttled = 1;
5051 cfs_rq->throttled_clock = rq_clock(rq);
5052 return true;
5053 }
5054
unthrottle_cfs_rq(struct cfs_rq * cfs_rq)5055 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
5056 {
5057 struct rq *rq = rq_of(cfs_rq);
5058 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5059 struct sched_entity *se;
5060 long task_delta, idle_task_delta;
5061 struct cfs_rq *tcfs_rq __maybe_unused = cfs_rq;
5062
5063 se = cfs_rq->tg->se[cpu_of(rq)];
5064
5065 cfs_rq->throttled = 0;
5066
5067 update_rq_clock(rq);
5068
5069 raw_spin_lock(&cfs_b->lock);
5070 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
5071 list_del_rcu(&cfs_rq->throttled_list);
5072 raw_spin_unlock(&cfs_b->lock);
5073
5074 /* update hierarchical throttle state */
5075 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
5076
5077 if (!cfs_rq->load.weight)
5078 return;
5079
5080 task_delta = cfs_rq->h_nr_running;
5081 idle_task_delta = cfs_rq->idle_h_nr_running;
5082 for_each_sched_entity(se) {
5083 if (se->on_rq)
5084 break;
5085 cfs_rq = cfs_rq_of(se);
5086 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
5087
5088 cfs_rq->h_nr_running += task_delta;
5089 cfs_rq->idle_h_nr_running += idle_task_delta;
5090 walt_inc_throttled_cfs_rq_stats(&cfs_rq->walt_stats, tcfs_rq);
5091
5092 /* end evaluation on encountering a throttled cfs_rq */
5093 if (cfs_rq_throttled(cfs_rq))
5094 goto unthrottle_throttle;
5095 }
5096
5097 for_each_sched_entity(se) {
5098 cfs_rq = cfs_rq_of(se);
5099
5100 update_load_avg(cfs_rq, se, UPDATE_TG);
5101 se_update_runnable(se);
5102
5103 cfs_rq->h_nr_running += task_delta;
5104 cfs_rq->idle_h_nr_running += idle_task_delta;
5105 walt_inc_throttled_cfs_rq_stats(&cfs_rq->walt_stats, tcfs_rq);
5106
5107 /* end evaluation on encountering a throttled cfs_rq */
5108 if (cfs_rq_throttled(cfs_rq))
5109 goto unthrottle_throttle;
5110
5111 /*
5112 * One parent has been throttled and cfs_rq removed from the
5113 * list. Add it back to not break the leaf list.
5114 */
5115 if (throttled_hierarchy(cfs_rq))
5116 list_add_leaf_cfs_rq(cfs_rq);
5117 }
5118
5119 /* At this point se is NULL and we are at root level*/
5120 add_nr_running(rq, task_delta);
5121 walt_inc_throttled_cfs_rq_stats(&rq->walt_stats, tcfs_rq);
5122
5123 unthrottle_throttle:
5124 /*
5125 * The cfs_rq_throttled() breaks in the above iteration can result in
5126 * incomplete leaf list maintenance, resulting in triggering the
5127 * assertion below.
5128 */
5129 for_each_sched_entity(se) {
5130 cfs_rq = cfs_rq_of(se);
5131
5132 if (list_add_leaf_cfs_rq(cfs_rq))
5133 break;
5134 }
5135
5136 assert_list_leaf_cfs_rq(rq);
5137
5138 /* Determine whether we need to wake up potentially idle CPU: */
5139 if (rq->curr == rq->idle && rq->cfs.nr_running)
5140 resched_curr(rq);
5141 }
5142
distribute_cfs_runtime(struct cfs_bandwidth * cfs_b)5143 static void distribute_cfs_runtime(struct cfs_bandwidth *cfs_b)
5144 {
5145 struct cfs_rq *cfs_rq;
5146 u64 runtime, remaining = 1;
5147
5148 rcu_read_lock();
5149 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
5150 throttled_list) {
5151 struct rq *rq = rq_of(cfs_rq);
5152 struct rq_flags rf;
5153
5154 rq_lock_irqsave(rq, &rf);
5155 if (!cfs_rq_throttled(cfs_rq))
5156 goto next;
5157
5158 /* By the above check, this should never be true */
5159 SCHED_WARN_ON(cfs_rq->runtime_remaining > 0);
5160
5161 raw_spin_lock(&cfs_b->lock);
5162 runtime = -cfs_rq->runtime_remaining + 1;
5163 if (runtime > cfs_b->runtime)
5164 runtime = cfs_b->runtime;
5165 cfs_b->runtime -= runtime;
5166 remaining = cfs_b->runtime;
5167 raw_spin_unlock(&cfs_b->lock);
5168
5169 cfs_rq->runtime_remaining += runtime;
5170
5171 /* we check whether we're throttled above */
5172 if (cfs_rq->runtime_remaining > 0)
5173 unthrottle_cfs_rq(cfs_rq);
5174
5175 next:
5176 rq_unlock_irqrestore(rq, &rf);
5177
5178 if (!remaining)
5179 break;
5180 }
5181 rcu_read_unlock();
5182 }
5183
5184 /*
5185 * Responsible for refilling a task_group's bandwidth and unthrottling its
5186 * cfs_rqs as appropriate. If there has been no activity within the last
5187 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
5188 * used to track this state.
5189 */
do_sched_cfs_period_timer(struct cfs_bandwidth * cfs_b,int overrun,unsigned long flags)5190 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags)
5191 {
5192 int throttled;
5193
5194 /* no need to continue the timer with no bandwidth constraint */
5195 if (cfs_b->quota == RUNTIME_INF)
5196 goto out_deactivate;
5197
5198 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5199 cfs_b->nr_periods += overrun;
5200
5201 /*
5202 * idle depends on !throttled (for the case of a large deficit), and if
5203 * we're going inactive then everything else can be deferred
5204 */
5205 if (cfs_b->idle && !throttled)
5206 goto out_deactivate;
5207
5208 __refill_cfs_bandwidth_runtime(cfs_b);
5209
5210 if (!throttled) {
5211 /* mark as potentially idle for the upcoming period */
5212 cfs_b->idle = 1;
5213 return 0;
5214 }
5215
5216 /* account preceding periods in which throttling occurred */
5217 cfs_b->nr_throttled += overrun;
5218
5219 /*
5220 * This check is repeated as we release cfs_b->lock while we unthrottle.
5221 */
5222 while (throttled && cfs_b->runtime > 0) {
5223 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5224 /* we can't nest cfs_b->lock while distributing bandwidth */
5225 distribute_cfs_runtime(cfs_b);
5226 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5227
5228 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
5229 }
5230
5231 /*
5232 * While we are ensured activity in the period following an
5233 * unthrottle, this also covers the case in which the new bandwidth is
5234 * insufficient to cover the existing bandwidth deficit. (Forcing the
5235 * timer to remain active while there are any throttled entities.)
5236 */
5237 cfs_b->idle = 0;
5238
5239 return 0;
5240
5241 out_deactivate:
5242 return 1;
5243 }
5244
5245 /* a cfs_rq won't donate quota below this amount */
5246 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
5247 /* minimum remaining period time to redistribute slack quota */
5248 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
5249 /* how long we wait to gather additional slack before distributing */
5250 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
5251
5252 /*
5253 * Are we near the end of the current quota period?
5254 *
5255 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
5256 * hrtimer base being cleared by hrtimer_start. In the case of
5257 * migrate_hrtimers, base is never cleared, so we are fine.
5258 */
runtime_refresh_within(struct cfs_bandwidth * cfs_b,u64 min_expire)5259 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
5260 {
5261 struct hrtimer *refresh_timer = &cfs_b->period_timer;
5262 s64 remaining;
5263
5264 /* if the call-back is running a quota refresh is already occurring */
5265 if (hrtimer_callback_running(refresh_timer))
5266 return 1;
5267
5268 /* is a quota refresh about to occur? */
5269 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
5270 if (remaining < (s64)min_expire)
5271 return 1;
5272
5273 return 0;
5274 }
5275
start_cfs_slack_bandwidth(struct cfs_bandwidth * cfs_b)5276 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
5277 {
5278 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
5279
5280 /* if there's a quota refresh soon don't bother with slack */
5281 if (runtime_refresh_within(cfs_b, min_left))
5282 return;
5283
5284 /* don't push forwards an existing deferred unthrottle */
5285 if (cfs_b->slack_started)
5286 return;
5287 cfs_b->slack_started = true;
5288
5289 hrtimer_start(&cfs_b->slack_timer,
5290 ns_to_ktime(cfs_bandwidth_slack_period),
5291 HRTIMER_MODE_REL);
5292 }
5293
5294 /* we know any runtime found here is valid as update_curr() precedes return */
__return_cfs_rq_runtime(struct cfs_rq * cfs_rq)5295 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5296 {
5297 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
5298 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
5299
5300 if (slack_runtime <= 0)
5301 return;
5302
5303 raw_spin_lock(&cfs_b->lock);
5304 if (cfs_b->quota != RUNTIME_INF) {
5305 cfs_b->runtime += slack_runtime;
5306
5307 /* we are under rq->lock, defer unthrottling using a timer */
5308 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
5309 !list_empty(&cfs_b->throttled_cfs_rq))
5310 start_cfs_slack_bandwidth(cfs_b);
5311 }
5312 raw_spin_unlock(&cfs_b->lock);
5313
5314 /* even if it's not valid for return we don't want to try again */
5315 cfs_rq->runtime_remaining -= slack_runtime;
5316 }
5317
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)5318 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5319 {
5320 if (!cfs_bandwidth_used())
5321 return;
5322
5323 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
5324 return;
5325
5326 __return_cfs_rq_runtime(cfs_rq);
5327 }
5328
5329 /*
5330 * This is done with a timer (instead of inline with bandwidth return) since
5331 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
5332 */
do_sched_cfs_slack_timer(struct cfs_bandwidth * cfs_b)5333 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
5334 {
5335 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
5336 unsigned long flags;
5337
5338 /* confirm we're still not at a refresh boundary */
5339 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5340 cfs_b->slack_started = false;
5341
5342 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
5343 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5344 return;
5345 }
5346
5347 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
5348 runtime = cfs_b->runtime;
5349
5350 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5351
5352 if (!runtime)
5353 return;
5354
5355 distribute_cfs_runtime(cfs_b);
5356
5357 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5358 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5359 }
5360
5361 /*
5362 * When a group wakes up we want to make sure that its quota is not already
5363 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
5364 * runtime as update_curr() throttling can not trigger until it's on-rq.
5365 */
check_enqueue_throttle(struct cfs_rq * cfs_rq)5366 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
5367 {
5368 if (!cfs_bandwidth_used())
5369 return;
5370
5371 /* an active group must be handled by the update_curr()->put() path */
5372 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
5373 return;
5374
5375 /* ensure the group is not already throttled */
5376 if (cfs_rq_throttled(cfs_rq))
5377 return;
5378
5379 /* update runtime allocation */
5380 account_cfs_rq_runtime(cfs_rq, 0);
5381 if (cfs_rq->runtime_remaining <= 0)
5382 throttle_cfs_rq(cfs_rq);
5383 }
5384
sync_throttle(struct task_group * tg,int cpu)5385 static void sync_throttle(struct task_group *tg, int cpu)
5386 {
5387 struct cfs_rq *pcfs_rq, *cfs_rq;
5388
5389 if (!cfs_bandwidth_used())
5390 return;
5391
5392 if (!tg->parent)
5393 return;
5394
5395 cfs_rq = tg->cfs_rq[cpu];
5396 pcfs_rq = tg->parent->cfs_rq[cpu];
5397
5398 cfs_rq->throttle_count = pcfs_rq->throttle_count;
5399 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu));
5400 }
5401
5402 /* conditionally throttle active cfs_rq's from put_prev_entity() */
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)5403 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5404 {
5405 if (!cfs_bandwidth_used())
5406 return false;
5407
5408 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
5409 return false;
5410
5411 /*
5412 * it's possible for a throttled entity to be forced into a running
5413 * state (e.g. set_curr_task), in this case we're finished.
5414 */
5415 if (cfs_rq_throttled(cfs_rq))
5416 return true;
5417
5418 return throttle_cfs_rq(cfs_rq);
5419 }
5420
sched_cfs_slack_timer(struct hrtimer * timer)5421 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
5422 {
5423 struct cfs_bandwidth *cfs_b =
5424 container_of(timer, struct cfs_bandwidth, slack_timer);
5425
5426 do_sched_cfs_slack_timer(cfs_b);
5427
5428 return HRTIMER_NORESTART;
5429 }
5430
5431 extern const u64 max_cfs_quota_period;
5432
sched_cfs_period_timer(struct hrtimer * timer)5433 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
5434 {
5435 struct cfs_bandwidth *cfs_b =
5436 container_of(timer, struct cfs_bandwidth, period_timer);
5437 unsigned long flags;
5438 int overrun;
5439 int idle = 0;
5440 int count = 0;
5441
5442 raw_spin_lock_irqsave(&cfs_b->lock, flags);
5443 for (;;) {
5444 overrun = hrtimer_forward_now(timer, cfs_b->period);
5445 if (!overrun)
5446 break;
5447
5448 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags);
5449
5450 if (++count > 3) {
5451 u64 new, old = ktime_to_ns(cfs_b->period);
5452
5453 /*
5454 * Grow period by a factor of 2 to avoid losing precision.
5455 * Precision loss in the quota/period ratio can cause __cfs_schedulable
5456 * to fail.
5457 */
5458 new = old * 2;
5459 if (new < max_cfs_quota_period) {
5460 cfs_b->period = ns_to_ktime(new);
5461 cfs_b->quota *= 2;
5462
5463 pr_warn_ratelimited(
5464 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5465 smp_processor_id(),
5466 div_u64(new, NSEC_PER_USEC),
5467 div_u64(cfs_b->quota, NSEC_PER_USEC));
5468 } else {
5469 pr_warn_ratelimited(
5470 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n",
5471 smp_processor_id(),
5472 div_u64(old, NSEC_PER_USEC),
5473 div_u64(cfs_b->quota, NSEC_PER_USEC));
5474 }
5475
5476 /* reset count so we don't come right back in here */
5477 count = 0;
5478 }
5479 }
5480 if (idle)
5481 cfs_b->period_active = 0;
5482 raw_spin_unlock_irqrestore(&cfs_b->lock, flags);
5483
5484 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
5485 }
5486
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5487 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5488 {
5489 raw_spin_lock_init(&cfs_b->lock);
5490 cfs_b->runtime = 0;
5491 cfs_b->quota = RUNTIME_INF;
5492 cfs_b->period = ns_to_ktime(default_cfs_period());
5493
5494 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
5495 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
5496 cfs_b->period_timer.function = sched_cfs_period_timer;
5497 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5498 cfs_b->slack_timer.function = sched_cfs_slack_timer;
5499 cfs_b->slack_started = false;
5500 }
5501
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)5502 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
5503 {
5504 cfs_rq->runtime_enabled = 0;
5505 INIT_LIST_HEAD(&cfs_rq->throttled_list);
5506 walt_init_cfs_rq_stats(cfs_rq);
5507 }
5508
start_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5509 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5510 {
5511 lockdep_assert_held(&cfs_b->lock);
5512
5513 if (cfs_b->period_active)
5514 return;
5515
5516 cfs_b->period_active = 1;
5517 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period);
5518 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED);
5519 }
5520
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5521 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
5522 {
5523 /* init_cfs_bandwidth() was not called */
5524 if (!cfs_b->throttled_cfs_rq.next)
5525 return;
5526
5527 hrtimer_cancel(&cfs_b->period_timer);
5528 hrtimer_cancel(&cfs_b->slack_timer);
5529 }
5530
5531 /*
5532 * Both these CPU hotplug callbacks race against unregister_fair_sched_group()
5533 *
5534 * The race is harmless, since modifying bandwidth settings of unhooked group
5535 * bits doesn't do much.
5536 */
5537
5538 /* cpu online calback */
update_runtime_enabled(struct rq * rq)5539 static void __maybe_unused update_runtime_enabled(struct rq *rq)
5540 {
5541 struct task_group *tg;
5542
5543 lockdep_assert_held(&rq->lock);
5544
5545 rcu_read_lock();
5546 list_for_each_entry_rcu(tg, &task_groups, list) {
5547 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
5548 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5549
5550 raw_spin_lock(&cfs_b->lock);
5551 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
5552 raw_spin_unlock(&cfs_b->lock);
5553 }
5554 rcu_read_unlock();
5555 }
5556
5557 /* cpu offline callback */
unthrottle_offline_cfs_rqs(struct rq * rq)5558 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
5559 {
5560 struct task_group *tg;
5561
5562 lockdep_assert_held(&rq->lock);
5563
5564 rcu_read_lock();
5565 list_for_each_entry_rcu(tg, &task_groups, list) {
5566 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
5567
5568 if (!cfs_rq->runtime_enabled)
5569 continue;
5570
5571 /*
5572 * clock_task is not advancing so we just need to make sure
5573 * there's some valid quota amount
5574 */
5575 cfs_rq->runtime_remaining = 1;
5576 /*
5577 * Offline rq is schedulable till CPU is completely disabled
5578 * in take_cpu_down(), so we prevent new cfs throttling here.
5579 */
5580 cfs_rq->runtime_enabled = 0;
5581
5582 if (cfs_rq_throttled(cfs_rq))
5583 unthrottle_cfs_rq(cfs_rq);
5584 }
5585 rcu_read_unlock();
5586 }
5587
5588 #else /* CONFIG_CFS_BANDWIDTH */
5589
cfs_bandwidth_used(void)5590 static inline bool cfs_bandwidth_used(void)
5591 {
5592 return false;
5593 }
5594
account_cfs_rq_runtime(struct cfs_rq * cfs_rq,u64 delta_exec)5595 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
check_cfs_rq_runtime(struct cfs_rq * cfs_rq)5596 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
check_enqueue_throttle(struct cfs_rq * cfs_rq)5597 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
sync_throttle(struct task_group * tg,int cpu)5598 static inline void sync_throttle(struct task_group *tg, int cpu) {}
return_cfs_rq_runtime(struct cfs_rq * cfs_rq)5599 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5600
cfs_rq_throttled(struct cfs_rq * cfs_rq)5601 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
5602 {
5603 return 0;
5604 }
5605
throttled_hierarchy(struct cfs_rq * cfs_rq)5606 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
5607 {
5608 return 0;
5609 }
5610
throttled_lb_pair(struct task_group * tg,int src_cpu,int dest_cpu)5611 static inline int throttled_lb_pair(struct task_group *tg,
5612 int src_cpu, int dest_cpu)
5613 {
5614 return 0;
5615 }
5616
init_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5617 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
5618
5619 #ifdef CONFIG_FAIR_GROUP_SCHED
init_cfs_rq_runtime(struct cfs_rq * cfs_rq)5620 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
5621 #endif
5622
tg_cfs_bandwidth(struct task_group * tg)5623 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
5624 {
5625 return NULL;
5626 }
destroy_cfs_bandwidth(struct cfs_bandwidth * cfs_b)5627 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
update_runtime_enabled(struct rq * rq)5628 static inline void update_runtime_enabled(struct rq *rq) {}
unthrottle_offline_cfs_rqs(struct rq * rq)5629 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
5630
5631 #endif /* CONFIG_CFS_BANDWIDTH */
5632
5633 /**************************************************
5634 * CFS operations on tasks:
5635 */
5636
5637 #ifdef CONFIG_SCHED_HRTICK
hrtick_start_fair(struct rq * rq,struct task_struct * p)5638 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
5639 {
5640 struct sched_entity *se = &p->se;
5641 struct cfs_rq *cfs_rq = cfs_rq_of(se);
5642
5643 SCHED_WARN_ON(task_rq(p) != rq);
5644
5645 if (rq->cfs.h_nr_running > 1) {
5646 u64 slice = sched_slice(cfs_rq, se);
5647 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
5648 s64 delta = slice - ran;
5649
5650 if (delta < 0) {
5651 if (rq->curr == p)
5652 resched_curr(rq);
5653 return;
5654 }
5655 hrtick_start(rq, delta);
5656 }
5657 }
5658
5659 /*
5660 * called from enqueue/dequeue and updates the hrtick when the
5661 * current task is from our class and nr_running is low enough
5662 * to matter.
5663 */
hrtick_update(struct rq * rq)5664 static void hrtick_update(struct rq *rq)
5665 {
5666 struct task_struct *curr = rq->curr;
5667
5668 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
5669 return;
5670
5671 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
5672 hrtick_start_fair(rq, curr);
5673 }
5674 #else /* !CONFIG_SCHED_HRTICK */
5675 static inline void
hrtick_start_fair(struct rq * rq,struct task_struct * p)5676 hrtick_start_fair(struct rq *rq, struct task_struct *p)
5677 {
5678 }
5679
hrtick_update(struct rq * rq)5680 static inline void hrtick_update(struct rq *rq)
5681 {
5682 }
5683 #endif
5684
5685 #ifdef CONFIG_SMP
cpu_overutilized(int cpu)5686 static inline bool cpu_overutilized(int cpu)
5687 {
5688 return !fits_capacity(cpu_util(cpu), capacity_of(cpu));
5689 }
5690
update_overutilized_status(struct rq * rq)5691 static inline void update_overutilized_status(struct rq *rq)
5692 {
5693 if (!READ_ONCE(rq->rd->overutilized) && cpu_overutilized(rq->cpu)) {
5694 WRITE_ONCE(rq->rd->overutilized, SG_OVERUTILIZED);
5695 trace_sched_overutilized_tp(rq->rd, SG_OVERUTILIZED);
5696 }
5697 }
5698 #else
update_overutilized_status(struct rq * rq)5699 static inline void update_overutilized_status(struct rq *rq) { }
5700 #endif
5701
5702 /* Runqueue only has SCHED_IDLE tasks enqueued */
sched_idle_rq(struct rq * rq)5703 static int sched_idle_rq(struct rq *rq)
5704 {
5705 return unlikely(rq->nr_running == rq->cfs.idle_h_nr_running &&
5706 rq->nr_running);
5707 }
5708
5709 #ifdef CONFIG_SMP
sched_idle_cpu(int cpu)5710 static int sched_idle_cpu(int cpu)
5711 {
5712 return sched_idle_rq(cpu_rq(cpu));
5713 }
5714 #endif
5715
5716 static void set_next_buddy(struct sched_entity *se);
5717
5718 #ifdef CONFIG_SCHED_LATENCY_NICE
check_preempt_from_idle(struct cfs_rq * cfs,struct sched_entity * se)5719 static void check_preempt_from_idle(struct cfs_rq *cfs, struct sched_entity *se)
5720 {
5721 struct sched_entity *next;
5722
5723 if (se->latency_weight <= 0)
5724 return;
5725
5726 if (cfs->nr_running <= 1)
5727 return;
5728 /*
5729 * When waking from idle, we don't need to check to preempt at wakeup
5730 * the idle thread and don't set next buddy as a candidate for being
5731 * picked in priority.
5732 * In case of simultaneous wakeup from idle, the latency sensitive tasks
5733 * lost opportunity to preempt non sensitive tasks which woke up
5734 * simultaneously.
5735 */
5736
5737 if (cfs->next)
5738 next = cfs->next;
5739 else
5740 next = __pick_first_entity(cfs);
5741
5742 if (next && wakeup_preempt_entity(next, se) == 1)
5743 set_next_buddy(se);
5744 }
5745 #endif
5746
5747 /*
5748 * The enqueue_task method is called before nr_running is
5749 * increased. Here we update the fair scheduling stats and
5750 * then put the task into the rbtree:
5751 */
5752 static void
enqueue_task_fair(struct rq * rq,struct task_struct * p,int flags)5753 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5754 {
5755 struct cfs_rq *cfs_rq;
5756 struct sched_entity *se = &p->se;
5757 int idle_h_nr_running = task_has_idle_policy(p);
5758 int task_new = !(flags & ENQUEUE_WAKEUP);
5759
5760 /*
5761 * The code below (indirectly) updates schedutil which looks at
5762 * the cfs_rq utilization to select a frequency.
5763 * Let's add the task's estimated utilization to the cfs_rq's
5764 * estimated utilization, before we update schedutil.
5765 */
5766 util_est_enqueue(&rq->cfs, p);
5767
5768 /*
5769 * If in_iowait is set, the code below may not trigger any cpufreq
5770 * utilization updates, so do it here explicitly with the IOWAIT flag
5771 * passed.
5772 */
5773 if (p->in_iowait)
5774 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT);
5775
5776 for_each_sched_entity(se) {
5777 if (se->on_rq)
5778 break;
5779 cfs_rq = cfs_rq_of(se);
5780 enqueue_entity(cfs_rq, se, flags);
5781
5782 cfs_rq->h_nr_running++;
5783 cfs_rq->idle_h_nr_running += idle_h_nr_running;
5784 walt_inc_cfs_rq_stats(cfs_rq, p);
5785
5786 /* end evaluation on encountering a throttled cfs_rq */
5787 if (cfs_rq_throttled(cfs_rq))
5788 goto enqueue_throttle;
5789
5790 flags = ENQUEUE_WAKEUP;
5791 }
5792
5793 for_each_sched_entity(se) {
5794 cfs_rq = cfs_rq_of(se);
5795
5796 update_load_avg(cfs_rq, se, UPDATE_TG);
5797 se_update_runnable(se);
5798 update_cfs_group(se);
5799
5800 cfs_rq->h_nr_running++;
5801 cfs_rq->idle_h_nr_running += idle_h_nr_running;
5802 walt_inc_cfs_rq_stats(cfs_rq, p);
5803
5804 /* end evaluation on encountering a throttled cfs_rq */
5805 if (cfs_rq_throttled(cfs_rq))
5806 goto enqueue_throttle;
5807
5808 /*
5809 * One parent has been throttled and cfs_rq removed from the
5810 * list. Add it back to not break the leaf list.
5811 */
5812 if (throttled_hierarchy(cfs_rq))
5813 list_add_leaf_cfs_rq(cfs_rq);
5814 }
5815
5816 /* At this point se is NULL and we are at root level*/
5817 add_nr_running(rq, 1);
5818 inc_rq_walt_stats(rq, p);
5819 /*
5820 * Since new tasks are assigned an initial util_avg equal to
5821 * half of the spare capacity of their CPU, tiny tasks have the
5822 * ability to cross the overutilized threshold, which will
5823 * result in the load balancer ruining all the task placement
5824 * done by EAS. As a way to mitigate that effect, do not account
5825 * for the first enqueue operation of new tasks during the
5826 * overutilized flag detection.
5827 *
5828 * A better way of solving this problem would be to wait for
5829 * the PELT signals of tasks to converge before taking them
5830 * into account, but that is not straightforward to implement,
5831 * and the following generally works well enough in practice.
5832 */
5833 if (!task_new)
5834 update_overutilized_status(rq);
5835
5836 #ifdef CONFIG_SCHED_LATENCY_NICE
5837 if (rq->curr == rq->idle)
5838 check_preempt_from_idle(cfs_rq_of(&p->se), &p->se);
5839 #endif
5840
5841 enqueue_throttle:
5842 if (cfs_bandwidth_used()) {
5843 /*
5844 * When bandwidth control is enabled; the cfs_rq_throttled()
5845 * breaks in the above iteration can result in incomplete
5846 * leaf list maintenance, resulting in triggering the assertion
5847 * below.
5848 */
5849 for_each_sched_entity(se) {
5850 cfs_rq = cfs_rq_of(se);
5851
5852 if (list_add_leaf_cfs_rq(cfs_rq))
5853 break;
5854 }
5855 }
5856
5857 assert_list_leaf_cfs_rq(rq);
5858
5859 hrtick_update(rq);
5860 }
5861
5862 /*
5863 * The dequeue_task method is called before nr_running is
5864 * decreased. We remove the task from the rbtree and
5865 * update the fair scheduling stats:
5866 */
dequeue_task_fair(struct rq * rq,struct task_struct * p,int flags)5867 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
5868 {
5869 struct cfs_rq *cfs_rq;
5870 struct sched_entity *se = &p->se;
5871 int task_sleep = flags & DEQUEUE_SLEEP;
5872 int idle_h_nr_running = task_has_idle_policy(p);
5873 bool was_sched_idle = sched_idle_rq(rq);
5874
5875 util_est_dequeue(&rq->cfs, p);
5876
5877 for_each_sched_entity(se) {
5878 cfs_rq = cfs_rq_of(se);
5879 dequeue_entity(cfs_rq, se, flags);
5880
5881 cfs_rq->h_nr_running--;
5882 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5883 walt_dec_cfs_rq_stats(cfs_rq, p);
5884
5885 /* end evaluation on encountering a throttled cfs_rq */
5886 if (cfs_rq_throttled(cfs_rq))
5887 goto dequeue_throttle;
5888
5889 /* Don't dequeue parent if it has other entities besides us */
5890 if (cfs_rq->load.weight) {
5891 /* Avoid re-evaluating load for this entity: */
5892 se = parent_entity(se);
5893 /*
5894 * Bias pick_next to pick a task from this cfs_rq, as
5895 * p is sleeping when it is within its sched_slice.
5896 */
5897 if (task_sleep && se && !throttled_hierarchy(cfs_rq))
5898 set_next_buddy(se);
5899 break;
5900 }
5901 flags |= DEQUEUE_SLEEP;
5902 }
5903
5904 for_each_sched_entity(se) {
5905 cfs_rq = cfs_rq_of(se);
5906
5907 update_load_avg(cfs_rq, se, UPDATE_TG);
5908 se_update_runnable(se);
5909 update_cfs_group(se);
5910
5911 cfs_rq->h_nr_running--;
5912 cfs_rq->idle_h_nr_running -= idle_h_nr_running;
5913 walt_dec_cfs_rq_stats(cfs_rq, p);
5914
5915 /* end evaluation on encountering a throttled cfs_rq */
5916 if (cfs_rq_throttled(cfs_rq))
5917 goto dequeue_throttle;
5918
5919 }
5920
5921 /* At this point se is NULL and we are at root level*/
5922 sub_nr_running(rq, 1);
5923 dec_rq_walt_stats(rq, p);
5924
5925 /* balance early to pull high priority tasks */
5926 if (unlikely(!was_sched_idle && sched_idle_rq(rq)))
5927 rq->next_balance = jiffies;
5928
5929 dequeue_throttle:
5930 util_est_update(&rq->cfs, p, task_sleep);
5931 hrtick_update(rq);
5932 }
5933
5934 #ifdef CONFIG_SMP
5935
5936 /* Working cpumask for: load_balance, load_balance_newidle. */
5937 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
5938 DEFINE_PER_CPU(cpumask_var_t, select_idle_mask);
5939
5940 #ifdef CONFIG_NO_HZ_COMMON
5941
5942 static struct {
5943 cpumask_var_t idle_cpus_mask;
5944 atomic_t nr_cpus;
5945 int has_blocked; /* Idle CPUS has blocked load */
5946 unsigned long next_balance; /* in jiffy units */
5947 unsigned long next_blocked; /* Next update of blocked load in jiffies */
5948 } nohz ____cacheline_aligned;
5949
5950 #endif /* CONFIG_NO_HZ_COMMON */
5951
cpu_load(struct rq * rq)5952 static unsigned long cpu_load(struct rq *rq)
5953 {
5954 return cfs_rq_load_avg(&rq->cfs);
5955 }
5956
5957 /*
5958 * cpu_load_without - compute CPU load without any contributions from *p
5959 * @cpu: the CPU which load is requested
5960 * @p: the task which load should be discounted
5961 *
5962 * The load of a CPU is defined by the load of tasks currently enqueued on that
5963 * CPU as well as tasks which are currently sleeping after an execution on that
5964 * CPU.
5965 *
5966 * This method returns the load of the specified CPU by discounting the load of
5967 * the specified task, whenever the task is currently contributing to the CPU
5968 * load.
5969 */
cpu_load_without(struct rq * rq,struct task_struct * p)5970 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p)
5971 {
5972 struct cfs_rq *cfs_rq;
5973 unsigned int load;
5974
5975 /* Task has no contribution or is new */
5976 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
5977 return cpu_load(rq);
5978
5979 cfs_rq = &rq->cfs;
5980 load = READ_ONCE(cfs_rq->avg.load_avg);
5981
5982 /* Discount task's util from CPU's util */
5983 lsub_positive(&load, task_h_load(p));
5984
5985 return load;
5986 }
5987
cpu_runnable(struct rq * rq)5988 static unsigned long cpu_runnable(struct rq *rq)
5989 {
5990 return cfs_rq_runnable_avg(&rq->cfs);
5991 }
5992
cpu_runnable_without(struct rq * rq,struct task_struct * p)5993 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p)
5994 {
5995 struct cfs_rq *cfs_rq;
5996 unsigned int runnable;
5997
5998 /* Task has no contribution or is new */
5999 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6000 return cpu_runnable(rq);
6001
6002 cfs_rq = &rq->cfs;
6003 runnable = READ_ONCE(cfs_rq->avg.runnable_avg);
6004
6005 /* Discount task's runnable from CPU's runnable */
6006 lsub_positive(&runnable, p->se.avg.runnable_avg);
6007
6008 return runnable;
6009 }
6010
record_wakee(struct task_struct * p)6011 static void record_wakee(struct task_struct *p)
6012 {
6013 /*
6014 * Only decay a single time; tasks that have less then 1 wakeup per
6015 * jiffy will not have built up many flips.
6016 */
6017 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
6018 current->wakee_flips >>= 1;
6019 current->wakee_flip_decay_ts = jiffies;
6020 }
6021
6022 if (current->last_wakee != p) {
6023 current->last_wakee = p;
6024 current->wakee_flips++;
6025 }
6026 }
6027
6028 /*
6029 * Detect M:N waker/wakee relationships via a switching-frequency heuristic.
6030 *
6031 * A waker of many should wake a different task than the one last awakened
6032 * at a frequency roughly N times higher than one of its wakees.
6033 *
6034 * In order to determine whether we should let the load spread vs consolidating
6035 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one
6036 * partner, and a factor of lls_size higher frequency in the other.
6037 *
6038 * With both conditions met, we can be relatively sure that the relationship is
6039 * non-monogamous, with partner count exceeding socket size.
6040 *
6041 * Waker/wakee being client/server, worker/dispatcher, interrupt source or
6042 * whatever is irrelevant, spread criteria is apparent partner count exceeds
6043 * socket size.
6044 */
wake_wide(struct task_struct * p)6045 static int wake_wide(struct task_struct *p)
6046 {
6047 unsigned int master = current->wakee_flips;
6048 unsigned int slave = p->wakee_flips;
6049 int factor = __this_cpu_read(sd_llc_size);
6050
6051 if (master < slave)
6052 swap(master, slave);
6053 if (slave < factor || master < slave * factor)
6054 return 0;
6055 return 1;
6056 }
6057
6058 /*
6059 * The purpose of wake_affine() is to quickly determine on which CPU we can run
6060 * soonest. For the purpose of speed we only consider the waking and previous
6061 * CPU.
6062 *
6063 * wake_affine_idle() - only considers 'now', it check if the waking CPU is
6064 * cache-affine and is (or will be) idle.
6065 *
6066 * wake_affine_weight() - considers the weight to reflect the average
6067 * scheduling latency of the CPUs. This seems to work
6068 * for the overloaded case.
6069 */
6070 static int
wake_affine_idle(int this_cpu,int prev_cpu,int sync)6071 wake_affine_idle(int this_cpu, int prev_cpu, int sync)
6072 {
6073 /*
6074 * If this_cpu is idle, it implies the wakeup is from interrupt
6075 * context. Only allow the move if cache is shared. Otherwise an
6076 * interrupt intensive workload could force all tasks onto one
6077 * node depending on the IO topology or IRQ affinity settings.
6078 *
6079 * If the prev_cpu is idle and cache affine then avoid a migration.
6080 * There is no guarantee that the cache hot data from an interrupt
6081 * is more important than cache hot data on the prev_cpu and from
6082 * a cpufreq perspective, it's better to have higher utilisation
6083 * on one CPU.
6084 */
6085 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu))
6086 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu;
6087
6088 if (sync && cpu_rq(this_cpu)->nr_running == 1)
6089 return this_cpu;
6090
6091 return nr_cpumask_bits;
6092 }
6093
6094 static int
wake_affine_weight(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)6095 wake_affine_weight(struct sched_domain *sd, struct task_struct *p,
6096 int this_cpu, int prev_cpu, int sync)
6097 {
6098 s64 this_eff_load, prev_eff_load;
6099 unsigned long task_load;
6100
6101 this_eff_load = cpu_load(cpu_rq(this_cpu));
6102
6103 if (sync) {
6104 unsigned long current_load = task_h_load(current);
6105
6106 if (current_load > this_eff_load)
6107 return this_cpu;
6108
6109 this_eff_load -= current_load;
6110 }
6111
6112 task_load = task_h_load(p);
6113
6114 this_eff_load += task_load;
6115 if (sched_feat(WA_BIAS))
6116 this_eff_load *= 100;
6117 this_eff_load *= capacity_of(prev_cpu);
6118
6119 prev_eff_load = cpu_load(cpu_rq(prev_cpu));
6120 prev_eff_load -= task_load;
6121 if (sched_feat(WA_BIAS))
6122 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2;
6123 prev_eff_load *= capacity_of(this_cpu);
6124
6125 /*
6126 * If sync, adjust the weight of prev_eff_load such that if
6127 * prev_eff == this_eff that select_idle_sibling() will consider
6128 * stacking the wakee on top of the waker if no other CPU is
6129 * idle.
6130 */
6131 if (sync)
6132 prev_eff_load += 1;
6133
6134 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits;
6135 }
6136
wake_affine(struct sched_domain * sd,struct task_struct * p,int this_cpu,int prev_cpu,int sync)6137 static int wake_affine(struct sched_domain *sd, struct task_struct *p,
6138 int this_cpu, int prev_cpu, int sync)
6139 {
6140 int target = nr_cpumask_bits;
6141
6142 if (sched_feat(WA_IDLE))
6143 target = wake_affine_idle(this_cpu, prev_cpu, sync);
6144
6145 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits)
6146 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync);
6147
6148 schedstat_inc(p->se.statistics.nr_wakeups_affine_attempts);
6149 if (target == nr_cpumask_bits)
6150 return prev_cpu;
6151
6152 schedstat_inc(sd->ttwu_move_affine);
6153 schedstat_inc(p->se.statistics.nr_wakeups_affine);
6154 return target;
6155 }
6156
6157 static struct sched_group *
6158 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu);
6159
6160 /*
6161 * find_idlest_group_cpu - find the idlest CPU among the CPUs in the group.
6162 */
6163 static int
find_idlest_group_cpu(struct sched_group * group,struct task_struct * p,int this_cpu)6164 find_idlest_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
6165 {
6166 unsigned long load, min_load = ULONG_MAX;
6167 unsigned int min_exit_latency = UINT_MAX;
6168 u64 latest_idle_timestamp = 0;
6169 int least_loaded_cpu = this_cpu;
6170 int shallowest_idle_cpu = -1;
6171 int i;
6172
6173 /* Check if we have any choice: */
6174 if (group->group_weight == 1)
6175 return cpumask_first(sched_group_span(group));
6176
6177 /* Traverse only the allowed CPUs */
6178 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) {
6179 if (cpu_isolated(i))
6180 continue;
6181
6182 if (sched_idle_cpu(i))
6183 return i;
6184
6185 if (available_idle_cpu(i)) {
6186 struct rq *rq = cpu_rq(i);
6187 struct cpuidle_state *idle = idle_get_state(rq);
6188 if (idle && idle->exit_latency < min_exit_latency) {
6189 /*
6190 * We give priority to a CPU whose idle state
6191 * has the smallest exit latency irrespective
6192 * of any idle timestamp.
6193 */
6194 min_exit_latency = idle->exit_latency;
6195 latest_idle_timestamp = rq->idle_stamp;
6196 shallowest_idle_cpu = i;
6197 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
6198 rq->idle_stamp > latest_idle_timestamp) {
6199 /*
6200 * If equal or no active idle state, then
6201 * the most recently idled CPU might have
6202 * a warmer cache.
6203 */
6204 latest_idle_timestamp = rq->idle_stamp;
6205 shallowest_idle_cpu = i;
6206 }
6207 } else if (shallowest_idle_cpu == -1) {
6208 load = cpu_load(cpu_rq(i));
6209 if (load < min_load) {
6210 min_load = load;
6211 least_loaded_cpu = i;
6212 }
6213 }
6214 }
6215
6216 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
6217 }
6218
find_idlest_cpu(struct sched_domain * sd,struct task_struct * p,int cpu,int prev_cpu,int sd_flag)6219 static inline int find_idlest_cpu(struct sched_domain *sd, struct task_struct *p,
6220 int cpu, int prev_cpu, int sd_flag)
6221 {
6222 int new_cpu = cpu;
6223
6224 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr))
6225 return prev_cpu;
6226
6227 /*
6228 * We need task's util for cpu_util_without, sync it up to
6229 * prev_cpu's last_update_time.
6230 */
6231 if (!(sd_flag & SD_BALANCE_FORK))
6232 sync_entity_load_avg(&p->se);
6233
6234 while (sd) {
6235 struct sched_group *group;
6236 struct sched_domain *tmp;
6237 int weight;
6238
6239 if (!(sd->flags & sd_flag)) {
6240 sd = sd->child;
6241 continue;
6242 }
6243
6244 group = find_idlest_group(sd, p, cpu);
6245 if (!group) {
6246 sd = sd->child;
6247 continue;
6248 }
6249
6250 new_cpu = find_idlest_group_cpu(group, p, cpu);
6251 if (new_cpu == cpu) {
6252 /* Now try balancing at a lower domain level of 'cpu': */
6253 sd = sd->child;
6254 continue;
6255 }
6256
6257 /* Now try balancing at a lower domain level of 'new_cpu': */
6258 cpu = new_cpu;
6259 weight = sd->span_weight;
6260 sd = NULL;
6261 for_each_domain(cpu, tmp) {
6262 if (weight <= tmp->span_weight)
6263 break;
6264 if (tmp->flags & sd_flag)
6265 sd = tmp;
6266 }
6267 }
6268
6269 return new_cpu;
6270 }
6271
6272 #ifdef CONFIG_SCHED_SMT
6273 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
6274 EXPORT_SYMBOL_GPL(sched_smt_present);
6275
set_idle_cores(int cpu,int val)6276 static inline void set_idle_cores(int cpu, int val)
6277 {
6278 struct sched_domain_shared *sds;
6279
6280 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6281 if (sds)
6282 WRITE_ONCE(sds->has_idle_cores, val);
6283 }
6284
test_idle_cores(int cpu,bool def)6285 static inline bool test_idle_cores(int cpu, bool def)
6286 {
6287 struct sched_domain_shared *sds;
6288
6289 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
6290 if (sds)
6291 return READ_ONCE(sds->has_idle_cores);
6292
6293 return def;
6294 }
6295
6296 /*
6297 * Scans the local SMT mask to see if the entire core is idle, and records this
6298 * information in sd_llc_shared->has_idle_cores.
6299 *
6300 * Since SMT siblings share all cache levels, inspecting this limited remote
6301 * state should be fairly cheap.
6302 */
__update_idle_core(struct rq * rq)6303 void __update_idle_core(struct rq *rq)
6304 {
6305 int core = cpu_of(rq);
6306 int cpu;
6307
6308 rcu_read_lock();
6309 if (test_idle_cores(core, true))
6310 goto unlock;
6311
6312 for_each_cpu(cpu, cpu_smt_mask(core)) {
6313 if (cpu == core)
6314 continue;
6315
6316 if (!available_idle_cpu(cpu))
6317 goto unlock;
6318 }
6319
6320 set_idle_cores(core, 1);
6321 unlock:
6322 rcu_read_unlock();
6323 }
6324
6325 /*
6326 * Scan the entire LLC domain for idle cores; this dynamically switches off if
6327 * there are no idle cores left in the system; tracked through
6328 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above.
6329 */
select_idle_core(struct task_struct * p,struct sched_domain * sd,int target)6330 static int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
6331 {
6332 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6333 int core, cpu;
6334
6335 if (!static_branch_likely(&sched_smt_present))
6336 return -1;
6337
6338 if (!test_idle_cores(target, false))
6339 return -1;
6340
6341 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6342 #ifdef CONFIG_CPU_ISOLATION_OPT
6343 cpumask_andnot(cpus, cpus, cpu_isolated_mask);
6344 #endif
6345
6346 for_each_cpu_wrap(core, cpus, target) {
6347 bool idle = true;
6348
6349 for_each_cpu(cpu, cpu_smt_mask(core)) {
6350 if (!available_idle_cpu(cpu)) {
6351 idle = false;
6352 break;
6353 }
6354 }
6355 cpumask_andnot(cpus, cpus, cpu_smt_mask(core));
6356
6357 if (idle)
6358 return core;
6359 }
6360
6361 /*
6362 * Failed to find an idle core; stop looking for one.
6363 */
6364 set_idle_cores(target, 0);
6365
6366 return -1;
6367 }
6368
6369 /*
6370 * Scan the local SMT mask for idle CPUs.
6371 */
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)6372 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6373 {
6374 int cpu;
6375
6376 if (!static_branch_likely(&sched_smt_present))
6377 return -1;
6378
6379 for_each_cpu(cpu, cpu_smt_mask(target)) {
6380 if (!cpumask_test_cpu(cpu, p->cpus_ptr) ||
6381 !cpumask_test_cpu(cpu, sched_domain_span(sd)))
6382 continue;
6383 if (cpu_isolated(cpu))
6384 continue;
6385 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
6386 return cpu;
6387 }
6388
6389 return -1;
6390 }
6391
6392 #else /* CONFIG_SCHED_SMT */
6393
select_idle_core(struct task_struct * p,struct sched_domain * sd,int target)6394 static inline int select_idle_core(struct task_struct *p, struct sched_domain *sd, int target)
6395 {
6396 return -1;
6397 }
6398
select_idle_smt(struct task_struct * p,struct sched_domain * sd,int target)6399 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target)
6400 {
6401 return -1;
6402 }
6403
6404 #endif /* CONFIG_SCHED_SMT */
6405
6406 /*
6407 * Scan the LLC domain for idle CPUs; this is dynamically regulated by
6408 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the
6409 * average idle time for this rq (as found in rq->avg_idle).
6410 */
select_idle_cpu(struct task_struct * p,struct sched_domain * sd,int target)6411 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, int target)
6412 {
6413 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6414 struct sched_domain *this_sd;
6415 u64 avg_cost, avg_idle;
6416 u64 time;
6417 int this = smp_processor_id();
6418 int cpu, nr = INT_MAX;
6419
6420 this_sd = rcu_dereference(*this_cpu_ptr(&sd_llc));
6421 if (!this_sd)
6422 return -1;
6423
6424 /*
6425 * Due to large variance we need a large fuzz factor; hackbench in
6426 * particularly is sensitive here.
6427 */
6428 avg_idle = this_rq()->avg_idle / 512;
6429 avg_cost = this_sd->avg_scan_cost + 1;
6430
6431 if (sched_feat(SIS_AVG_CPU) && avg_idle < avg_cost)
6432 return -1;
6433
6434 if (sched_feat(SIS_PROP)) {
6435 u64 span_avg = sd->span_weight * avg_idle;
6436 if (span_avg > 4*avg_cost)
6437 nr = div_u64(span_avg, avg_cost);
6438 else
6439 nr = 4;
6440 }
6441
6442 time = cpu_clock(this);
6443
6444 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6445
6446 for_each_cpu_wrap(cpu, cpus, target) {
6447 if (!--nr)
6448 return -1;
6449 if (cpu_isolated(cpu))
6450 continue;
6451 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu))
6452 break;
6453 }
6454
6455 time = cpu_clock(this) - time;
6456 update_avg(&this_sd->avg_scan_cost, time);
6457
6458 return cpu;
6459 }
6460
6461 /*
6462 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which
6463 * the task fits. If no CPU is big enough, but there are idle ones, try to
6464 * maximize capacity.
6465 */
6466 static int
select_idle_capacity(struct task_struct * p,struct sched_domain * sd,int target)6467 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target)
6468 {
6469 unsigned long task_util, best_cap = 0;
6470 int cpu, best_cpu = -1;
6471 struct cpumask *cpus;
6472
6473 cpus = this_cpu_cpumask_var_ptr(select_idle_mask);
6474 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr);
6475
6476 task_util = uclamp_task_util(p);
6477
6478 for_each_cpu_wrap(cpu, cpus, target) {
6479 unsigned long cpu_cap = capacity_of(cpu);
6480
6481 if (cpu_isolated(cpu))
6482 continue;
6483
6484 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu))
6485 continue;
6486 if (fits_capacity(task_util, cpu_cap))
6487 return cpu;
6488
6489 if (cpu_cap > best_cap) {
6490 best_cap = cpu_cap;
6491 best_cpu = cpu;
6492 }
6493 }
6494
6495 return best_cpu;
6496 }
6497
asym_fits_capacity(unsigned long task_util,int cpu)6498 static inline bool asym_fits_capacity(unsigned long task_util, int cpu)
6499 {
6500 if (static_branch_unlikely(&sched_asym_cpucapacity))
6501 return fits_capacity(task_util, capacity_of(cpu));
6502
6503 return true;
6504 }
6505
6506 /*
6507 * Try and locate an idle core/thread in the LLC cache domain.
6508 */
select_idle_sibling(struct task_struct * p,int prev,int target)6509 static int select_idle_sibling(struct task_struct *p, int prev, int target)
6510 {
6511 struct sched_domain *sd;
6512 unsigned long task_util;
6513 int i, recent_used_cpu;
6514
6515 /*
6516 * On asymmetric system, update task utilization because we will check
6517 * that the task fits with cpu's capacity.
6518 */
6519 if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6520 sync_entity_load_avg(&p->se);
6521 task_util = uclamp_task_util(p);
6522 }
6523
6524 if ((available_idle_cpu(target) || sched_idle_cpu(target)) &&
6525 !cpu_isolated(target) && asym_fits_capacity(task_util, target))
6526 return target;
6527
6528 /*
6529 * If the previous CPU is cache affine and idle, don't be stupid:
6530 */
6531 if (prev != target && cpus_share_cache(prev, target) &&
6532 ((available_idle_cpu(prev) || sched_idle_cpu(prev)) &&
6533 !cpu_isolated(target) && asym_fits_capacity(task_util, prev)))
6534 return prev;
6535
6536 /*
6537 * Allow a per-cpu kthread to stack with the wakee if the
6538 * kworker thread and the tasks previous CPUs are the same.
6539 * The assumption is that the wakee queued work for the
6540 * per-cpu kthread that is now complete and the wakeup is
6541 * essentially a sync wakeup. An obvious example of this
6542 * pattern is IO completions.
6543 */
6544 if (is_per_cpu_kthread(current) &&
6545 in_task() &&
6546 prev == smp_processor_id() &&
6547 this_rq()->nr_running <= 1 &&
6548 asym_fits_capacity(task_util, prev)) {
6549 return prev;
6550 }
6551
6552 /* Check a recently used CPU as a potential idle candidate: */
6553 recent_used_cpu = p->recent_used_cpu;
6554 if (recent_used_cpu != prev &&
6555 recent_used_cpu != target &&
6556 cpus_share_cache(recent_used_cpu, target) &&
6557 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) &&
6558 cpumask_test_cpu(p->recent_used_cpu, p->cpus_ptr) &&
6559 asym_fits_capacity(task_util, recent_used_cpu)) {
6560 /*
6561 * Replace recent_used_cpu with prev as it is a potential
6562 * candidate for the next wake:
6563 */
6564 p->recent_used_cpu = prev;
6565 return recent_used_cpu;
6566 }
6567
6568 /*
6569 * For asymmetric CPU capacity systems, our domain of interest is
6570 * sd_asym_cpucapacity rather than sd_llc.
6571 */
6572 if (static_branch_unlikely(&sched_asym_cpucapacity)) {
6573 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, target));
6574 /*
6575 * On an asymmetric CPU capacity system where an exclusive
6576 * cpuset defines a symmetric island (i.e. one unique
6577 * capacity_orig value through the cpuset), the key will be set
6578 * but the CPUs within that cpuset will not have a domain with
6579 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric
6580 * capacity path.
6581 */
6582 if (sd) {
6583 i = select_idle_capacity(p, sd, target);
6584 return ((unsigned)i < nr_cpumask_bits) ? i : target;
6585 }
6586 }
6587
6588 sd = rcu_dereference(per_cpu(sd_llc, target));
6589 if (!sd)
6590 return target;
6591
6592 i = select_idle_core(p, sd, target);
6593 if ((unsigned)i < nr_cpumask_bits)
6594 return i;
6595
6596 i = select_idle_cpu(p, sd, target);
6597 if ((unsigned)i < nr_cpumask_bits)
6598 return i;
6599
6600 i = select_idle_smt(p, sd, target);
6601 if ((unsigned)i < nr_cpumask_bits)
6602 return i;
6603
6604 return target;
6605 }
6606
6607 /**
6608 * Amount of capacity of a CPU that is (estimated to be) used by CFS tasks
6609 * @cpu: the CPU to get the utilization of
6610 *
6611 * The unit of the return value must be the one of capacity so we can compare
6612 * the utilization with the capacity of the CPU that is available for CFS task
6613 * (ie cpu_capacity).
6614 *
6615 * cfs_rq.avg.util_avg is the sum of running time of runnable tasks plus the
6616 * recent utilization of currently non-runnable tasks on a CPU. It represents
6617 * the amount of utilization of a CPU in the range [0..capacity_orig] where
6618 * capacity_orig is the cpu_capacity available at the highest frequency
6619 * (arch_scale_freq_capacity()).
6620 * The utilization of a CPU converges towards a sum equal to or less than the
6621 * current capacity (capacity_curr <= capacity_orig) of the CPU because it is
6622 * the running time on this CPU scaled by capacity_curr.
6623 *
6624 * The estimated utilization of a CPU is defined to be the maximum between its
6625 * cfs_rq.avg.util_avg and the sum of the estimated utilization of the tasks
6626 * currently RUNNABLE on that CPU.
6627 * This allows to properly represent the expected utilization of a CPU which
6628 * has just got a big task running since a long sleep period. At the same time
6629 * however it preserves the benefits of the "blocked utilization" in
6630 * describing the potential for other tasks waking up on the same CPU.
6631 *
6632 * Nevertheless, cfs_rq.avg.util_avg can be higher than capacity_curr or even
6633 * higher than capacity_orig because of unfortunate rounding in
6634 * cfs.avg.util_avg or just after migrating tasks and new task wakeups until
6635 * the average stabilizes with the new running time. We need to check that the
6636 * utilization stays within the range of [0..capacity_orig] and cap it if
6637 * necessary. Without utilization capping, a group could be seen as overloaded
6638 * (CPU0 utilization at 121% + CPU1 utilization at 80%) whereas CPU1 has 20% of
6639 * available capacity. We allow utilization to overshoot capacity_curr (but not
6640 * capacity_orig) as it useful for predicting the capacity required after task
6641 * migrations (scheduler-driven DVFS).
6642 *
6643 * Return: the (estimated) utilization for the specified CPU
6644 */
cpu_util(int cpu)6645 unsigned long cpu_util(int cpu)
6646 {
6647 struct cfs_rq *cfs_rq;
6648 unsigned int util;
6649
6650 #ifdef CONFIG_SCHED_WALT
6651 if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util)) {
6652 u64 walt_cpu_util =
6653 cpu_rq(cpu)->walt_stats.cumulative_runnable_avg_scaled;
6654
6655 return min_t(unsigned long, walt_cpu_util,
6656 capacity_orig_of(cpu));
6657 }
6658 #endif
6659
6660 cfs_rq = &cpu_rq(cpu)->cfs;
6661 util = READ_ONCE(cfs_rq->avg.util_avg);
6662
6663 if (sched_feat(UTIL_EST))
6664 util = max(util, READ_ONCE(cfs_rq->avg.util_est.enqueued));
6665
6666 return min_t(unsigned long, util, capacity_orig_of(cpu));
6667 }
6668
6669 /*
6670 * cpu_util_without: compute cpu utilization without any contributions from *p
6671 * @cpu: the CPU which utilization is requested
6672 * @p: the task which utilization should be discounted
6673 *
6674 * The utilization of a CPU is defined by the utilization of tasks currently
6675 * enqueued on that CPU as well as tasks which are currently sleeping after an
6676 * execution on that CPU.
6677 *
6678 * This method returns the utilization of the specified CPU by discounting the
6679 * utilization of the specified task, whenever the task is currently
6680 * contributing to the CPU utilization.
6681 */
cpu_util_without(int cpu,struct task_struct * p)6682 static unsigned long cpu_util_without(int cpu, struct task_struct *p)
6683 {
6684 struct cfs_rq *cfs_rq;
6685 unsigned int util;
6686
6687 #ifdef CONFIG_SCHED_WALT
6688 /*
6689 * WALT does not decay idle tasks in the same manner
6690 * as PELT, so it makes little sense to subtract task
6691 * utilization from cpu utilization. Instead just use
6692 * cpu_util for this case.
6693 */
6694 if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util) &&
6695 p->state == TASK_WAKING)
6696 return cpu_util(cpu);
6697 #endif
6698
6699 /* Task has no contribution or is new */
6700 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
6701 return cpu_util(cpu);
6702
6703 #ifdef CONFIG_SCHED_WALT
6704 if (likely(!walt_disabled && sysctl_sched_use_walt_cpu_util)) {
6705 util = max_t(long, cpu_util(cpu) - task_util(p), 0);
6706 return min_t(unsigned long, util, capacity_orig_of(cpu));
6707 }
6708 #endif
6709
6710 cfs_rq = &cpu_rq(cpu)->cfs;
6711 util = READ_ONCE(cfs_rq->avg.util_avg);
6712
6713 /* Discount task's util from CPU's util */
6714 lsub_positive(&util, task_util(p));
6715
6716 /*
6717 * Covered cases:
6718 *
6719 * a) if *p is the only task sleeping on this CPU, then:
6720 * cpu_util (== task_util) > util_est (== 0)
6721 * and thus we return:
6722 * cpu_util_without = (cpu_util - task_util) = 0
6723 *
6724 * b) if other tasks are SLEEPING on this CPU, which is now exiting
6725 * IDLE, then:
6726 * cpu_util >= task_util
6727 * cpu_util > util_est (== 0)
6728 * and thus we discount *p's blocked utilization to return:
6729 * cpu_util_without = (cpu_util - task_util) >= 0
6730 *
6731 * c) if other tasks are RUNNABLE on that CPU and
6732 * util_est > cpu_util
6733 * then we use util_est since it returns a more restrictive
6734 * estimation of the spare capacity on that CPU, by just
6735 * considering the expected utilization of tasks already
6736 * runnable on that CPU.
6737 *
6738 * Cases a) and b) are covered by the above code, while case c) is
6739 * covered by the following code when estimated utilization is
6740 * enabled.
6741 */
6742 if (sched_feat(UTIL_EST)) {
6743 unsigned int estimated =
6744 READ_ONCE(cfs_rq->avg.util_est.enqueued);
6745
6746 /*
6747 * Despite the following checks we still have a small window
6748 * for a possible race, when an execl's select_task_rq_fair()
6749 * races with LB's detach_task():
6750 *
6751 * detach_task()
6752 * p->on_rq = TASK_ON_RQ_MIGRATING;
6753 * ---------------------------------- A
6754 * deactivate_task() \
6755 * dequeue_task() + RaceTime
6756 * util_est_dequeue() /
6757 * ---------------------------------- B
6758 *
6759 * The additional check on "current == p" it's required to
6760 * properly fix the execl regression and it helps in further
6761 * reducing the chances for the above race.
6762 */
6763 if (unlikely(task_on_rq_queued(p) || current == p))
6764 lsub_positive(&estimated, _task_util_est(p));
6765
6766 util = max(util, estimated);
6767 }
6768
6769 /*
6770 * Utilization (estimated) can exceed the CPU capacity, thus let's
6771 * clamp to the maximum CPU capacity to ensure consistency with
6772 * the cpu_util call.
6773 */
6774 return min_t(unsigned long, util, capacity_orig_of(cpu));
6775 }
6776
6777 #ifdef CONFIG_SCHED_RTG
capacity_spare_without(int cpu,struct task_struct * p)6778 unsigned long capacity_spare_without(int cpu, struct task_struct *p)
6779 {
6780 return max_t(long, capacity_of(cpu) - cpu_util_without(cpu, p), 0);
6781 }
6782 #endif
6783 /*
6784 * Predicts what cpu_util(@cpu) would return if @p was migrated (and enqueued)
6785 * to @dst_cpu.
6786 */
cpu_util_next(int cpu,struct task_struct * p,int dst_cpu)6787 static unsigned long cpu_util_next(int cpu, struct task_struct *p, int dst_cpu)
6788 {
6789 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs;
6790 unsigned long util_est, util = READ_ONCE(cfs_rq->avg.util_avg);
6791
6792 /*
6793 * If @p migrates from @cpu to another, remove its contribution. Or,
6794 * if @p migrates from another CPU to @cpu, add its contribution. In
6795 * the other cases, @cpu is not impacted by the migration, so the
6796 * util_avg should already be correct.
6797 */
6798 if (task_cpu(p) == cpu && dst_cpu != cpu)
6799 sub_positive(&util, task_util(p));
6800 else if (task_cpu(p) != cpu && dst_cpu == cpu)
6801 util += task_util(p);
6802
6803 if (sched_feat(UTIL_EST)) {
6804 util_est = READ_ONCE(cfs_rq->avg.util_est.enqueued);
6805
6806 /*
6807 * During wake-up, the task isn't enqueued yet and doesn't
6808 * appear in the cfs_rq->avg.util_est.enqueued of any rq,
6809 * so just add it (if needed) to "simulate" what will be
6810 * cpu_util() after the task has been enqueued.
6811 */
6812 if (dst_cpu == cpu)
6813 util_est += _task_util_est(p);
6814
6815 util = max(util, util_est);
6816 }
6817
6818 return min(util, capacity_orig_of(cpu));
6819 }
6820
6821 /*
6822 * Returns the current capacity of cpu after applying both
6823 * cpu and freq scaling.
6824 */
capacity_curr_of(int cpu)6825 unsigned long capacity_curr_of(int cpu)
6826 {
6827 unsigned long max_cap = cpu_rq(cpu)->cpu_capacity_orig;
6828 unsigned long scale_freq = arch_scale_freq_capacity(cpu);
6829
6830 return cap_scale(max_cap, scale_freq);
6831 }
6832
6833 /*
6834 * compute_energy(): Estimates the energy that @pd would consume if @p was
6835 * migrated to @dst_cpu. compute_energy() predicts what will be the utilization
6836 * landscape of @pd's CPUs after the task migration, and uses the Energy Model
6837 * to compute what would be the energy if we decided to actually migrate that
6838 * task.
6839 */
6840 static long
compute_energy(struct task_struct * p,int dst_cpu,struct perf_domain * pd)6841 compute_energy(struct task_struct *p, int dst_cpu, struct perf_domain *pd)
6842 {
6843 struct cpumask *pd_mask = perf_domain_span(pd);
6844 unsigned long cpu_cap = arch_scale_cpu_capacity(cpumask_first(pd_mask));
6845 unsigned long max_util = 0, sum_util = 0;
6846 int cpu;
6847
6848 /*
6849 * The capacity state of CPUs of the current rd can be driven by CPUs
6850 * of another rd if they belong to the same pd. So, account for the
6851 * utilization of these CPUs too by masking pd with cpu_online_mask
6852 * instead of the rd span.
6853 *
6854 * If an entire pd is outside of the current rd, it will not appear in
6855 * its pd list and will not be accounted by compute_energy().
6856 */
6857 for_each_cpu_and(cpu, pd_mask, cpu_online_mask) {
6858 unsigned long cpu_util, util_cfs = cpu_util_next(cpu, p, dst_cpu);
6859 struct task_struct *tsk = cpu == dst_cpu ? p : NULL;
6860
6861 /*
6862 * Busy time computation: utilization clamping is not
6863 * required since the ratio (sum_util / cpu_capacity)
6864 * is already enough to scale the EM reported power
6865 * consumption at the (eventually clamped) cpu_capacity.
6866 */
6867 sum_util += schedutil_cpu_util(cpu, util_cfs, cpu_cap,
6868 ENERGY_UTIL, NULL);
6869
6870 /*
6871 * Performance domain frequency: utilization clamping
6872 * must be considered since it affects the selection
6873 * of the performance domain frequency.
6874 * NOTE: in case RT tasks are running, by default the
6875 * FREQUENCY_UTIL's utilization can be max OPP.
6876 */
6877 cpu_util = schedutil_cpu_util(cpu, util_cfs, cpu_cap,
6878 FREQUENCY_UTIL, tsk);
6879 max_util = max(max_util, cpu_util);
6880 }
6881
6882 return em_cpu_energy(pd->em_pd, max_util, sum_util);
6883 }
6884
6885 /*
6886 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the
6887 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum
6888 * spare capacity in each performance domain and uses it as a potential
6889 * candidate to execute the task. Then, it uses the Energy Model to figure
6890 * out which of the CPU candidates is the most energy-efficient.
6891 *
6892 * The rationale for this heuristic is as follows. In a performance domain,
6893 * all the most energy efficient CPU candidates (according to the Energy
6894 * Model) are those for which we'll request a low frequency. When there are
6895 * several CPUs for which the frequency request will be the same, we don't
6896 * have enough data to break the tie between them, because the Energy Model
6897 * only includes active power costs. With this model, if we assume that
6898 * frequency requests follow utilization (e.g. using schedutil), the CPU with
6899 * the maximum spare capacity in a performance domain is guaranteed to be among
6900 * the best candidates of the performance domain.
6901 *
6902 * In practice, it could be preferable from an energy standpoint to pack
6903 * small tasks on a CPU in order to let other CPUs go in deeper idle states,
6904 * but that could also hurt our chances to go cluster idle, and we have no
6905 * ways to tell with the current Energy Model if this is actually a good
6906 * idea or not. So, find_energy_efficient_cpu() basically favors
6907 * cluster-packing, and spreading inside a cluster. That should at least be
6908 * a good thing for latency, and this is consistent with the idea that most
6909 * of the energy savings of EAS come from the asymmetry of the system, and
6910 * not so much from breaking the tie between identical CPUs. That's also the
6911 * reason why EAS is enabled in the topology code only for systems where
6912 * SD_ASYM_CPUCAPACITY is set.
6913 *
6914 * NOTE: Forkees are not accepted in the energy-aware wake-up path because
6915 * they don't have any useful utilization data yet and it's not possible to
6916 * forecast their impact on energy consumption. Consequently, they will be
6917 * placed by find_idlest_cpu() on the least loaded CPU, which might turn out
6918 * to be energy-inefficient in some use-cases. The alternative would be to
6919 * bias new tasks towards specific types of CPUs first, or to try to infer
6920 * their util_avg from the parent task, but those heuristics could hurt
6921 * other use-cases too. So, until someone finds a better way to solve this,
6922 * let's keep things simple by re-using the existing slow path.
6923 */
find_energy_efficient_cpu(struct task_struct * p,int prev_cpu)6924 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu)
6925 {
6926 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX;
6927 struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
6928 unsigned long cpu_cap, util, base_energy = 0;
6929 int cpu, best_energy_cpu = prev_cpu;
6930 struct sched_domain *sd;
6931 struct perf_domain *pd;
6932
6933 rcu_read_lock();
6934 pd = rcu_dereference(rd->pd);
6935 if (!pd || READ_ONCE(rd->overutilized))
6936 goto fail;
6937
6938 /*
6939 * Energy-aware wake-up happens on the lowest sched_domain starting
6940 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu.
6941 */
6942 sd = rcu_dereference(*this_cpu_ptr(&sd_asym_cpucapacity));
6943 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
6944 sd = sd->parent;
6945 if (!sd)
6946 goto fail;
6947
6948 sync_entity_load_avg(&p->se);
6949 if (!task_util_est(p))
6950 goto unlock;
6951
6952 for (; pd; pd = pd->next) {
6953 unsigned long cur_delta, spare_cap, max_spare_cap = 0;
6954 unsigned long base_energy_pd;
6955 int max_spare_cap_cpu = -1;
6956
6957 /* Compute the 'base' energy of the pd, without @p */
6958 base_energy_pd = compute_energy(p, -1, pd);
6959 base_energy += base_energy_pd;
6960
6961 for_each_cpu_and(cpu, perf_domain_span(pd), sched_domain_span(sd)) {
6962 if (!cpumask_test_cpu(cpu, p->cpus_ptr))
6963 continue;
6964
6965 util = cpu_util_next(cpu, p, cpu);
6966 cpu_cap = capacity_of(cpu);
6967 spare_cap = cpu_cap;
6968 lsub_positive(&spare_cap, util);
6969
6970 /*
6971 * Skip CPUs that cannot satisfy the capacity request.
6972 * IOW, placing the task there would make the CPU
6973 * overutilized. Take uclamp into account to see how
6974 * much capacity we can get out of the CPU; this is
6975 * aligned with schedutil_cpu_util().
6976 */
6977 util = uclamp_rq_util_with(cpu_rq(cpu), util, p);
6978 if (!fits_capacity(util, cpu_cap))
6979 continue;
6980
6981 /* Always use prev_cpu as a candidate. */
6982 if (cpu == prev_cpu) {
6983 prev_delta = compute_energy(p, prev_cpu, pd);
6984 prev_delta -= base_energy_pd;
6985 best_delta = min(best_delta, prev_delta);
6986 }
6987
6988 /*
6989 * Find the CPU with the maximum spare capacity in
6990 * the performance domain
6991 */
6992 if (spare_cap > max_spare_cap) {
6993 max_spare_cap = spare_cap;
6994 max_spare_cap_cpu = cpu;
6995 }
6996 }
6997
6998 /* Evaluate the energy impact of using this CPU. */
6999 if (max_spare_cap_cpu >= 0 && max_spare_cap_cpu != prev_cpu) {
7000 cur_delta = compute_energy(p, max_spare_cap_cpu, pd);
7001 cur_delta -= base_energy_pd;
7002 if (cur_delta < best_delta) {
7003 best_delta = cur_delta;
7004 best_energy_cpu = max_spare_cap_cpu;
7005 }
7006 }
7007 }
7008 unlock:
7009 rcu_read_unlock();
7010
7011 /*
7012 * Pick the best CPU if prev_cpu cannot be used, or if it saves at
7013 * least 6% of the energy used by prev_cpu.
7014 */
7015 if (prev_delta == ULONG_MAX)
7016 return best_energy_cpu;
7017
7018 if ((prev_delta - best_delta) > ((prev_delta + base_energy) >> 4))
7019 return best_energy_cpu;
7020
7021 return prev_cpu;
7022
7023 fail:
7024 rcu_read_unlock();
7025
7026 return -1;
7027 }
7028
7029 /*
7030 * select_task_rq_fair: Select target runqueue for the waking task in domains
7031 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
7032 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
7033 *
7034 * Balances load by selecting the idlest CPU in the idlest group, or under
7035 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set.
7036 *
7037 * Returns the target CPU number.
7038 *
7039 * preempt must be disabled.
7040 */
7041 static int
select_task_rq_fair(struct task_struct * p,int prev_cpu,int sd_flag,int wake_flags)7042 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
7043 {
7044 struct sched_domain *tmp, *sd = NULL;
7045 int cpu = smp_processor_id();
7046 int new_cpu = prev_cpu;
7047 int want_affine = 0;
7048 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING);
7049 #ifdef CONFIG_SCHED_RTG
7050 int target_cpu = -1;
7051 target_cpu = find_rtg_cpu(p);
7052 if (target_cpu >= 0)
7053 return target_cpu;
7054 #endif
7055
7056 if (sd_flag & SD_BALANCE_WAKE) {
7057 record_wakee(p);
7058
7059 if (sched_energy_enabled()) {
7060 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
7061 if (new_cpu >= 0)
7062 return new_cpu;
7063 new_cpu = prev_cpu;
7064 }
7065
7066 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr);
7067 }
7068
7069 rcu_read_lock();
7070 for_each_domain(cpu, tmp) {
7071 /*
7072 * If both 'cpu' and 'prev_cpu' are part of this domain,
7073 * cpu is a valid SD_WAKE_AFFINE target.
7074 */
7075 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
7076 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
7077 if (cpu != prev_cpu)
7078 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync);
7079
7080 sd = NULL; /* Prefer wake_affine over balance flags */
7081 break;
7082 }
7083
7084 if (tmp->flags & sd_flag)
7085 sd = tmp;
7086 else if (!want_affine)
7087 break;
7088 }
7089
7090 if (unlikely(sd)) {
7091 /* Slow path */
7092 new_cpu = find_idlest_cpu(sd, p, cpu, prev_cpu, sd_flag);
7093 } else if (sd_flag & SD_BALANCE_WAKE) { /* XXX always ? */
7094 /* Fast path */
7095
7096 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu);
7097
7098 if (want_affine)
7099 current->recent_used_cpu = cpu;
7100 }
7101 rcu_read_unlock();
7102
7103 return new_cpu;
7104 }
7105
7106 static void detach_entity_cfs_rq(struct sched_entity *se);
7107
7108 /*
7109 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and
7110 * cfs_rq_of(p) references at time of call are still valid and identify the
7111 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held.
7112 */
migrate_task_rq_fair(struct task_struct * p,int new_cpu)7113 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu)
7114 {
7115 /*
7116 * As blocked tasks retain absolute vruntime the migration needs to
7117 * deal with this by subtracting the old and adding the new
7118 * min_vruntime -- the latter is done by enqueue_entity() when placing
7119 * the task on the new runqueue.
7120 */
7121 if (p->state == TASK_WAKING) {
7122 struct sched_entity *se = &p->se;
7123 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7124 u64 min_vruntime;
7125
7126 #ifndef CONFIG_64BIT
7127 u64 min_vruntime_copy;
7128
7129 do {
7130 min_vruntime_copy = cfs_rq->min_vruntime_copy;
7131 smp_rmb();
7132 min_vruntime = cfs_rq->min_vruntime;
7133 } while (min_vruntime != min_vruntime_copy);
7134 #else
7135 min_vruntime = cfs_rq->min_vruntime;
7136 #endif
7137
7138 se->vruntime -= min_vruntime;
7139 }
7140
7141 if (p->on_rq == TASK_ON_RQ_MIGRATING) {
7142 /*
7143 * In case of TASK_ON_RQ_MIGRATING we in fact hold the 'old'
7144 * rq->lock and can modify state directly.
7145 */
7146 lockdep_assert_held(&task_rq(p)->lock);
7147 detach_entity_cfs_rq(&p->se);
7148
7149 } else {
7150 /*
7151 * We are supposed to update the task to "current" time, then
7152 * its up to date and ready to go to new CPU/cfs_rq. But we
7153 * have difficulty in getting what current time is, so simply
7154 * throw away the out-of-date time. This will result in the
7155 * wakee task is less decayed, but giving the wakee more load
7156 * sounds not bad.
7157 */
7158 remove_entity_load_avg(&p->se);
7159 }
7160
7161 /* Tell new CPU we are migrated */
7162 p->se.avg.last_update_time = 0;
7163
7164 /* We have migrated, no longer consider this task hot */
7165 p->se.exec_start = 0;
7166
7167 update_scan_period(p, new_cpu);
7168 }
7169
task_dead_fair(struct task_struct * p)7170 static void task_dead_fair(struct task_struct *p)
7171 {
7172 remove_entity_load_avg(&p->se);
7173 }
7174
7175 static int
balance_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)7176 balance_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7177 {
7178 if (rq->nr_running)
7179 return 1;
7180
7181 return newidle_balance(rq, rf) != 0;
7182 }
7183 #endif /* CONFIG_SMP */
7184
7185 #ifdef CONFIG_SCHED_LATENCY_NICE
wakeup_latency_gran(struct sched_entity * curr,struct sched_entity * se)7186 static long wakeup_latency_gran(struct sched_entity *curr, struct sched_entity *se)
7187 {
7188 int latency_weight = se->latency_weight;
7189 long thresh = sysctl_sched_latency;
7190
7191 /*
7192 * A positive latency weigth means that the sched_entity has latency
7193 * requirement that needs to be evaluated versus other entity.
7194 * Otherwise, use the latency weight to evaluate how much scheduling
7195 * delay is acceptable by se.
7196 */
7197 if ((se->latency_weight > 0) || (curr->latency_weight > 0))
7198 latency_weight -= curr->latency_weight;
7199
7200 if (!latency_weight)
7201 return 0;
7202
7203 if (sched_feat(GENTLE_FAIR_SLEEPERS))
7204 thresh >>= 1;
7205
7206 /*
7207 * Clamp the delta to stay in the scheduler period range
7208 * [-sysctl_sched_latency:sysctl_sched_latency]
7209 */
7210 latency_weight = clamp_t(long, latency_weight,
7211 -1 * NICE_LATENCY_WEIGHT_MAX,
7212 NICE_LATENCY_WEIGHT_MAX);
7213
7214 return (thresh * latency_weight) >> NICE_LATENCY_SHIFT;
7215 }
7216 #endif
7217
wakeup_gran(struct sched_entity * se)7218 static unsigned long wakeup_gran(struct sched_entity *se)
7219 {
7220 unsigned long gran = sysctl_sched_wakeup_granularity;
7221
7222 /*
7223 * Since its curr running now, convert the gran from real-time
7224 * to virtual-time in his units.
7225 *
7226 * By using 'se' instead of 'curr' we penalize light tasks, so
7227 * they get preempted easier. That is, if 'se' < 'curr' then
7228 * the resulting gran will be larger, therefore penalizing the
7229 * lighter, if otoh 'se' > 'curr' then the resulting gran will
7230 * be smaller, again penalizing the lighter task.
7231 *
7232 * This is especially important for buddies when the leftmost
7233 * task is higher priority than the buddy.
7234 */
7235 return calc_delta_fair(gran, se);
7236 }
7237
7238 /*
7239 * Should 'se' preempt 'curr'.
7240 *
7241 * |s1
7242 * |s2
7243 * |s3
7244 * g
7245 * |<--->|c
7246 *
7247 * w(c, s1) = -1
7248 * w(c, s2) = 0
7249 * w(c, s3) = 1
7250 *
7251 */
7252 static int
wakeup_preempt_entity(struct sched_entity * curr,struct sched_entity * se)7253 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
7254 {
7255 s64 gran, vdiff = curr->vruntime - se->vruntime;
7256
7257 #ifdef CONFIG_SCHED_LATENCY_NICE
7258 /* Take into account latency priority */
7259 vdiff += wakeup_latency_gran(curr, se);
7260 #endif
7261
7262 if (vdiff <= 0)
7263 return -1;
7264
7265 gran = wakeup_gran(se);
7266 if (vdiff > gran)
7267 return 1;
7268
7269 return 0;
7270 }
7271
set_last_buddy(struct sched_entity * se)7272 static void set_last_buddy(struct sched_entity *se)
7273 {
7274 if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
7275 return;
7276
7277 for_each_sched_entity(se) {
7278 if (SCHED_WARN_ON(!se->on_rq))
7279 return;
7280 cfs_rq_of(se)->last = se;
7281 }
7282 }
7283
set_next_buddy(struct sched_entity * se)7284 static void set_next_buddy(struct sched_entity *se)
7285 {
7286 if (entity_is_task(se) && unlikely(task_has_idle_policy(task_of(se))))
7287 return;
7288
7289 for_each_sched_entity(se) {
7290 if (SCHED_WARN_ON(!se->on_rq))
7291 return;
7292 cfs_rq_of(se)->next = se;
7293 }
7294 }
7295
set_skip_buddy(struct sched_entity * se)7296 static void set_skip_buddy(struct sched_entity *se)
7297 {
7298 for_each_sched_entity(se)
7299 cfs_rq_of(se)->skip = se;
7300 }
7301
7302 /*
7303 * Preempt the current task with a newly woken task if needed:
7304 */
check_preempt_wakeup(struct rq * rq,struct task_struct * p,int wake_flags)7305 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
7306 {
7307 struct task_struct *curr = rq->curr;
7308 struct sched_entity *se = &curr->se, *pse = &p->se;
7309 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7310 int scale = cfs_rq->nr_running >= sched_nr_latency;
7311 int next_buddy_marked = 0;
7312
7313 if (unlikely(se == pse))
7314 return;
7315
7316 /*
7317 * This is possible from callers such as attach_tasks(), in which we
7318 * unconditionally check_prempt_curr() after an enqueue (which may have
7319 * lead to a throttle). This both saves work and prevents false
7320 * next-buddy nomination below.
7321 */
7322 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
7323 return;
7324
7325 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
7326 set_next_buddy(pse);
7327 next_buddy_marked = 1;
7328 }
7329
7330 /*
7331 * We can come here with TIF_NEED_RESCHED already set from new task
7332 * wake up path.
7333 *
7334 * Note: this also catches the edge-case of curr being in a throttled
7335 * group (e.g. via set_curr_task), since update_curr() (in the
7336 * enqueue of curr) will have resulted in resched being set. This
7337 * prevents us from potentially nominating it as a false LAST_BUDDY
7338 * below.
7339 */
7340 if (test_tsk_need_resched(curr))
7341 return;
7342
7343 /* Idle tasks are by definition preempted by non-idle tasks. */
7344 if (unlikely(task_has_idle_policy(curr)) &&
7345 likely(!task_has_idle_policy(p)))
7346 goto preempt;
7347
7348 /*
7349 * Batch and idle tasks do not preempt non-idle tasks (their preemption
7350 * is driven by the tick):
7351 */
7352 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
7353 return;
7354
7355 find_matching_se(&se, &pse);
7356 update_curr(cfs_rq_of(se));
7357 BUG_ON(!pse);
7358 if (wakeup_preempt_entity(se, pse) == 1) {
7359 /*
7360 * Bias pick_next to pick the sched entity that is
7361 * triggering this preemption.
7362 */
7363 if (!next_buddy_marked)
7364 set_next_buddy(pse);
7365 goto preempt;
7366 }
7367
7368 return;
7369
7370 preempt:
7371 resched_curr(rq);
7372 /*
7373 * Only set the backward buddy when the current task is still
7374 * on the rq. This can happen when a wakeup gets interleaved
7375 * with schedule on the ->pre_schedule() or idle_balance()
7376 * point, either of which can * drop the rq lock.
7377 *
7378 * Also, during early boot the idle thread is in the fair class,
7379 * for obvious reasons its a bad idea to schedule back to it.
7380 */
7381 if (unlikely(!se->on_rq || curr == rq->idle))
7382 return;
7383
7384 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
7385 set_last_buddy(se);
7386 }
7387
7388 struct task_struct *
pick_next_task_fair(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)7389 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
7390 {
7391 struct cfs_rq *cfs_rq = &rq->cfs;
7392 struct sched_entity *se;
7393 struct task_struct *p;
7394 int new_tasks;
7395
7396 again:
7397 if (!sched_fair_runnable(rq))
7398 goto idle;
7399
7400 #ifdef CONFIG_FAIR_GROUP_SCHED
7401 if (!prev || prev->sched_class != &fair_sched_class)
7402 goto simple;
7403
7404 /*
7405 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
7406 * likely that a next task is from the same cgroup as the current.
7407 *
7408 * Therefore attempt to avoid putting and setting the entire cgroup
7409 * hierarchy, only change the part that actually changes.
7410 */
7411
7412 do {
7413 struct sched_entity *curr = cfs_rq->curr;
7414
7415 /*
7416 * Since we got here without doing put_prev_entity() we also
7417 * have to consider cfs_rq->curr. If it is still a runnable
7418 * entity, update_curr() will update its vruntime, otherwise
7419 * forget we've ever seen it.
7420 */
7421 if (curr) {
7422 if (curr->on_rq)
7423 update_curr(cfs_rq);
7424 else
7425 curr = NULL;
7426
7427 /*
7428 * This call to check_cfs_rq_runtime() will do the
7429 * throttle and dequeue its entity in the parent(s).
7430 * Therefore the nr_running test will indeed
7431 * be correct.
7432 */
7433 if (unlikely(check_cfs_rq_runtime(cfs_rq))) {
7434 cfs_rq = &rq->cfs;
7435
7436 if (!cfs_rq->nr_running)
7437 goto idle;
7438
7439 goto simple;
7440 }
7441 }
7442
7443 se = pick_next_entity(cfs_rq, curr);
7444 cfs_rq = group_cfs_rq(se);
7445 } while (cfs_rq);
7446
7447 p = task_of(se);
7448
7449 /*
7450 * Since we haven't yet done put_prev_entity and if the selected task
7451 * is a different task than we started out with, try and touch the
7452 * least amount of cfs_rqs.
7453 */
7454 if (prev != p) {
7455 struct sched_entity *pse = &prev->se;
7456
7457 while (!(cfs_rq = is_same_group(se, pse))) {
7458 int se_depth = se->depth;
7459 int pse_depth = pse->depth;
7460
7461 if (se_depth <= pse_depth) {
7462 put_prev_entity(cfs_rq_of(pse), pse);
7463 pse = parent_entity(pse);
7464 }
7465 if (se_depth >= pse_depth) {
7466 set_next_entity(cfs_rq_of(se), se);
7467 se = parent_entity(se);
7468 }
7469 }
7470
7471 put_prev_entity(cfs_rq, pse);
7472 set_next_entity(cfs_rq, se);
7473 }
7474
7475 goto done;
7476 simple:
7477 #endif
7478 if (prev)
7479 put_prev_task(rq, prev);
7480
7481 do {
7482 se = pick_next_entity(cfs_rq, NULL);
7483 set_next_entity(cfs_rq, se);
7484 cfs_rq = group_cfs_rq(se);
7485 } while (cfs_rq);
7486
7487 p = task_of(se);
7488
7489 done: __maybe_unused;
7490 #ifdef CONFIG_SMP
7491 /*
7492 * Move the next running task to the front of
7493 * the list, so our cfs_tasks list becomes MRU
7494 * one.
7495 */
7496 list_move(&p->se.group_node, &rq->cfs_tasks);
7497 #endif
7498
7499 if (hrtick_enabled(rq))
7500 hrtick_start_fair(rq, p);
7501
7502 update_misfit_status(p, rq);
7503
7504 return p;
7505
7506 idle:
7507 if (!rf)
7508 return NULL;
7509
7510 new_tasks = newidle_balance(rq, rf);
7511
7512 /*
7513 * Because newidle_balance() releases (and re-acquires) rq->lock, it is
7514 * possible for any higher priority task to appear. In that case we
7515 * must re-start the pick_next_entity() loop.
7516 */
7517 if (new_tasks < 0)
7518 return RETRY_TASK;
7519
7520 if (new_tasks > 0)
7521 goto again;
7522
7523 /*
7524 * rq is about to be idle, check if we need to update the
7525 * lost_idle_time of clock_pelt
7526 */
7527 update_idle_rq_clock_pelt(rq);
7528
7529 return NULL;
7530 }
7531
__pick_next_task_fair(struct rq * rq)7532 static struct task_struct *__pick_next_task_fair(struct rq *rq)
7533 {
7534 return pick_next_task_fair(rq, NULL, NULL);
7535 }
7536
7537 /*
7538 * Account for a descheduled task:
7539 */
put_prev_task_fair(struct rq * rq,struct task_struct * prev)7540 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
7541 {
7542 struct sched_entity *se = &prev->se;
7543 struct cfs_rq *cfs_rq;
7544
7545 for_each_sched_entity(se) {
7546 cfs_rq = cfs_rq_of(se);
7547 put_prev_entity(cfs_rq, se);
7548 }
7549 }
7550
7551 /*
7552 * sched_yield() is very simple
7553 *
7554 * The magic of dealing with the ->skip buddy is in pick_next_entity.
7555 */
yield_task_fair(struct rq * rq)7556 static void yield_task_fair(struct rq *rq)
7557 {
7558 struct task_struct *curr = rq->curr;
7559 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
7560 struct sched_entity *se = &curr->se;
7561
7562 /*
7563 * Are we the only task in the tree?
7564 */
7565 if (unlikely(rq->nr_running == 1))
7566 return;
7567
7568 clear_buddies(cfs_rq, se);
7569
7570 if (curr->policy != SCHED_BATCH) {
7571 update_rq_clock(rq);
7572 /*
7573 * Update run-time statistics of the 'current'.
7574 */
7575 update_curr(cfs_rq);
7576 /*
7577 * Tell update_rq_clock() that we've just updated,
7578 * so we don't do microscopic update in schedule()
7579 * and double the fastpath cost.
7580 */
7581 rq_clock_skip_update(rq);
7582 }
7583
7584 set_skip_buddy(se);
7585 }
7586
yield_to_task_fair(struct rq * rq,struct task_struct * p)7587 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p)
7588 {
7589 struct sched_entity *se = &p->se;
7590
7591 /* throttled hierarchies are not runnable */
7592 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
7593 return false;
7594
7595 /* Tell the scheduler that we'd really like pse to run next. */
7596 set_next_buddy(se);
7597
7598 yield_task_fair(rq);
7599
7600 return true;
7601 }
7602
7603 #ifdef CONFIG_SMP
7604 /**************************************************
7605 * Fair scheduling class load-balancing methods.
7606 *
7607 * BASICS
7608 *
7609 * The purpose of load-balancing is to achieve the same basic fairness the
7610 * per-CPU scheduler provides, namely provide a proportional amount of compute
7611 * time to each task. This is expressed in the following equation:
7612 *
7613 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
7614 *
7615 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight
7616 * W_i,0 is defined as:
7617 *
7618 * W_i,0 = \Sum_j w_i,j (2)
7619 *
7620 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight
7621 * is derived from the nice value as per sched_prio_to_weight[].
7622 *
7623 * The weight average is an exponential decay average of the instantaneous
7624 * weight:
7625 *
7626 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
7627 *
7628 * C_i is the compute capacity of CPU i, typically it is the
7629 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
7630 * can also include other factors [XXX].
7631 *
7632 * To achieve this balance we define a measure of imbalance which follows
7633 * directly from (1):
7634 *
7635 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
7636 *
7637 * We them move tasks around to minimize the imbalance. In the continuous
7638 * function space it is obvious this converges, in the discrete case we get
7639 * a few fun cases generally called infeasible weight scenarios.
7640 *
7641 * [XXX expand on:
7642 * - infeasible weights;
7643 * - local vs global optima in the discrete case. ]
7644 *
7645 *
7646 * SCHED DOMAINS
7647 *
7648 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
7649 * for all i,j solution, we create a tree of CPUs that follows the hardware
7650 * topology where each level pairs two lower groups (or better). This results
7651 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the
7652 * tree to only the first of the previous level and we decrease the frequency
7653 * of load-balance at each level inv. proportional to the number of CPUs in
7654 * the groups.
7655 *
7656 * This yields:
7657 *
7658 * log_2 n 1 n
7659 * \Sum { --- * --- * 2^i } = O(n) (5)
7660 * i = 0 2^i 2^i
7661 * `- size of each group
7662 * | | `- number of CPUs doing load-balance
7663 * | `- freq
7664 * `- sum over all levels
7665 *
7666 * Coupled with a limit on how many tasks we can migrate every balance pass,
7667 * this makes (5) the runtime complexity of the balancer.
7668 *
7669 * An important property here is that each CPU is still (indirectly) connected
7670 * to every other CPU in at most O(log n) steps:
7671 *
7672 * The adjacency matrix of the resulting graph is given by:
7673 *
7674 * log_2 n
7675 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
7676 * k = 0
7677 *
7678 * And you'll find that:
7679 *
7680 * A^(log_2 n)_i,j != 0 for all i,j (7)
7681 *
7682 * Showing there's indeed a path between every CPU in at most O(log n) steps.
7683 * The task movement gives a factor of O(m), giving a convergence complexity
7684 * of:
7685 *
7686 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
7687 *
7688 *
7689 * WORK CONSERVING
7690 *
7691 * In order to avoid CPUs going idle while there's still work to do, new idle
7692 * balancing is more aggressive and has the newly idle CPU iterate up the domain
7693 * tree itself instead of relying on other CPUs to bring it work.
7694 *
7695 * This adds some complexity to both (5) and (8) but it reduces the total idle
7696 * time.
7697 *
7698 * [XXX more?]
7699 *
7700 *
7701 * CGROUPS
7702 *
7703 * Cgroups make a horror show out of (2), instead of a simple sum we get:
7704 *
7705 * s_k,i
7706 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
7707 * S_k
7708 *
7709 * Where
7710 *
7711 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
7712 *
7713 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i.
7714 *
7715 * The big problem is S_k, its a global sum needed to compute a local (W_i)
7716 * property.
7717 *
7718 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
7719 * rewrite all of this once again.]
7720 */
7721
7722 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
7723
7724 enum fbq_type { regular, remote, all };
7725
7726 /*
7727 * 'group_type' describes the group of CPUs at the moment of load balancing.
7728 *
7729 * The enum is ordered by pulling priority, with the group with lowest priority
7730 * first so the group_type can simply be compared when selecting the busiest
7731 * group. See update_sd_pick_busiest().
7732 */
7733 enum group_type {
7734 /* The group has spare capacity that can be used to run more tasks. */
7735 group_has_spare = 0,
7736 /*
7737 * The group is fully used and the tasks don't compete for more CPU
7738 * cycles. Nevertheless, some tasks might wait before running.
7739 */
7740 group_fully_busy,
7741 /*
7742 * SD_ASYM_CPUCAPACITY only: One task doesn't fit with CPU's capacity
7743 * and must be migrated to a more powerful CPU.
7744 */
7745 group_misfit_task,
7746 /*
7747 * SD_ASYM_PACKING only: One local CPU with higher capacity is available,
7748 * and the task should be migrated to it instead of running on the
7749 * current CPU.
7750 */
7751 group_asym_packing,
7752 /*
7753 * The tasks' affinity constraints previously prevented the scheduler
7754 * from balancing the load across the system.
7755 */
7756 group_imbalanced,
7757 /*
7758 * The CPU is overloaded and can't provide expected CPU cycles to all
7759 * tasks.
7760 */
7761 group_overloaded
7762 };
7763
7764 enum migration_type {
7765 migrate_load = 0,
7766 migrate_util,
7767 migrate_task,
7768 migrate_misfit
7769 };
7770
7771 #define LBF_ALL_PINNED 0x01
7772 #define LBF_NEED_BREAK 0x02
7773 #define LBF_DST_PINNED 0x04
7774 #define LBF_SOME_PINNED 0x08
7775 #define LBF_NOHZ_STATS 0x10
7776 #define LBF_NOHZ_AGAIN 0x20
7777 #define LBF_IGNORE_PREFERRED_CLUSTER_TASKS 0x200
7778
7779 struct lb_env {
7780 struct sched_domain *sd;
7781
7782 struct rq *src_rq;
7783 int src_cpu;
7784
7785 int dst_cpu;
7786 struct rq *dst_rq;
7787
7788 struct cpumask *dst_grpmask;
7789 int new_dst_cpu;
7790 enum cpu_idle_type idle;
7791 long imbalance;
7792 /* The set of CPUs under consideration for load-balancing */
7793 struct cpumask *cpus;
7794
7795 unsigned int flags;
7796
7797 unsigned int loop;
7798 unsigned int loop_break;
7799 unsigned int loop_max;
7800
7801 enum fbq_type fbq_type;
7802 enum migration_type migration_type;
7803 struct list_head tasks;
7804 };
7805
7806 /*
7807 * Is this task likely cache-hot:
7808 */
task_hot(struct task_struct * p,struct lb_env * env)7809 static int task_hot(struct task_struct *p, struct lb_env *env)
7810 {
7811 s64 delta;
7812
7813 lockdep_assert_held(&env->src_rq->lock);
7814
7815 if (p->sched_class != &fair_sched_class)
7816 return 0;
7817
7818 if (unlikely(task_has_idle_policy(p)))
7819 return 0;
7820
7821 /* SMT siblings share cache */
7822 if (env->sd->flags & SD_SHARE_CPUCAPACITY)
7823 return 0;
7824
7825 /*
7826 * Buddy candidates are cache hot:
7827 */
7828 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
7829 (&p->se == cfs_rq_of(&p->se)->next ||
7830 &p->se == cfs_rq_of(&p->se)->last))
7831 return 1;
7832
7833 if (sysctl_sched_migration_cost == -1)
7834 return 1;
7835 if (sysctl_sched_migration_cost == 0)
7836 return 0;
7837
7838 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
7839
7840 return delta < (s64)sysctl_sched_migration_cost;
7841 }
7842
7843 #ifdef CONFIG_NUMA_BALANCING
7844 /*
7845 * Returns 1, if task migration degrades locality
7846 * Returns 0, if task migration improves locality i.e migration preferred.
7847 * Returns -1, if task migration is not affected by locality.
7848 */
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)7849 static int migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
7850 {
7851 struct numa_group *numa_group = rcu_dereference(p->numa_group);
7852 unsigned long src_weight, dst_weight;
7853 int src_nid, dst_nid, dist;
7854
7855 if (!static_branch_likely(&sched_numa_balancing))
7856 return -1;
7857
7858 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
7859 return -1;
7860
7861 src_nid = cpu_to_node(env->src_cpu);
7862 dst_nid = cpu_to_node(env->dst_cpu);
7863
7864 if (src_nid == dst_nid)
7865 return -1;
7866
7867 /* Migrating away from the preferred node is always bad. */
7868 if (src_nid == p->numa_preferred_nid) {
7869 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running)
7870 return 1;
7871 else
7872 return -1;
7873 }
7874
7875 /* Encourage migration to the preferred node. */
7876 if (dst_nid == p->numa_preferred_nid)
7877 return 0;
7878
7879 /* Leaving a core idle is often worse than degrading locality. */
7880 if (env->idle == CPU_IDLE)
7881 return -1;
7882
7883 dist = node_distance(src_nid, dst_nid);
7884 if (numa_group) {
7885 src_weight = group_weight(p, src_nid, dist);
7886 dst_weight = group_weight(p, dst_nid, dist);
7887 } else {
7888 src_weight = task_weight(p, src_nid, dist);
7889 dst_weight = task_weight(p, dst_nid, dist);
7890 }
7891
7892 return dst_weight < src_weight;
7893 }
7894
7895 #else
migrate_degrades_locality(struct task_struct * p,struct lb_env * env)7896 static inline int migrate_degrades_locality(struct task_struct *p,
7897 struct lb_env *env)
7898 {
7899 return -1;
7900 }
7901 #endif
7902
7903 /*
7904 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
7905 */
7906 static
can_migrate_task(struct task_struct * p,struct lb_env * env)7907 int can_migrate_task(struct task_struct *p, struct lb_env *env)
7908 {
7909 int tsk_cache_hot;
7910
7911 lockdep_assert_held(&env->src_rq->lock);
7912
7913 /*
7914 * We do not migrate tasks that are:
7915 * 1) throttled_lb_pair, or
7916 * 2) cannot be migrated to this CPU due to cpus_ptr, or
7917 * 3) running (obviously), or
7918 * 4) are cache-hot on their current CPU.
7919 */
7920 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
7921 return 0;
7922
7923 /* Disregard pcpu kthreads; they are where they need to be. */
7924 if (kthread_is_per_cpu(p))
7925 return 0;
7926
7927 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) {
7928 int cpu;
7929
7930 schedstat_inc(p->se.statistics.nr_failed_migrations_affine);
7931
7932 env->flags |= LBF_SOME_PINNED;
7933
7934 /*
7935 * Remember if this task can be migrated to any other CPU in
7936 * our sched_group. We may want to revisit it if we couldn't
7937 * meet load balance goals by pulling other tasks on src_cpu.
7938 *
7939 * Avoid computing new_dst_cpu for NEWLY_IDLE or if we have
7940 * already computed one in current iteration.
7941 */
7942 if (env->idle == CPU_NEWLY_IDLE || (env->flags & LBF_DST_PINNED))
7943 return 0;
7944
7945 /* Prevent to re-select dst_cpu via env's CPUs: */
7946 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
7947 if (cpumask_test_cpu(cpu, p->cpus_ptr)) {
7948 env->flags |= LBF_DST_PINNED;
7949 env->new_dst_cpu = cpu;
7950 break;
7951 }
7952 }
7953
7954 return 0;
7955 }
7956
7957 /* Record that we found atleast one task that could run on dst_cpu */
7958 env->flags &= ~LBF_ALL_PINNED;
7959
7960
7961 #ifdef CONFIG_SCHED_RTG
7962 if (env->flags & LBF_IGNORE_PREFERRED_CLUSTER_TASKS &&
7963 !preferred_cluster(cpu_rq(env->dst_cpu)->cluster, p))
7964 return 0;
7965 #endif
7966
7967 if (task_running(env->src_rq, p)) {
7968 schedstat_inc(p->se.statistics.nr_failed_migrations_running);
7969 return 0;
7970 }
7971
7972 /*
7973 * Aggressive migration if:
7974 * 1) destination numa is preferred
7975 * 2) task is cache cold, or
7976 * 3) too many balance attempts have failed.
7977 */
7978 tsk_cache_hot = migrate_degrades_locality(p, env);
7979 if (tsk_cache_hot == -1)
7980 tsk_cache_hot = task_hot(p, env);
7981
7982 if (tsk_cache_hot <= 0 ||
7983 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
7984 if (tsk_cache_hot == 1) {
7985 schedstat_inc(env->sd->lb_hot_gained[env->idle]);
7986 schedstat_inc(p->se.statistics.nr_forced_migrations);
7987 }
7988 return 1;
7989 }
7990
7991 schedstat_inc(p->se.statistics.nr_failed_migrations_hot);
7992 return 0;
7993 }
7994
7995 /*
7996 * detach_task() -- detach the task for the migration specified in env
7997 */
detach_task(struct task_struct * p,struct lb_env * env)7998 static void detach_task(struct task_struct *p, struct lb_env *env)
7999 {
8000 lockdep_assert_held(&env->src_rq->lock);
8001
8002 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK);
8003 #ifdef CONFIG_SCHED_WALT
8004 double_lock_balance(env->src_rq, env->dst_rq);
8005 if (!(env->src_rq->clock_update_flags & RQCF_UPDATED))
8006 update_rq_clock(env->src_rq);
8007 #endif
8008 set_task_cpu(p, env->dst_cpu);
8009 #ifdef CONFIG_SCHED_WALT
8010 double_unlock_balance(env->src_rq, env->dst_rq);
8011 #endif
8012 }
8013
8014 /*
8015 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
8016 * part of active balancing operations within "domain".
8017 *
8018 * Returns a task if successful and NULL otherwise.
8019 */
detach_one_task(struct lb_env * env)8020 static struct task_struct *detach_one_task(struct lb_env *env)
8021 {
8022 struct task_struct *p;
8023
8024 lockdep_assert_held(&env->src_rq->lock);
8025
8026 list_for_each_entry_reverse(p,
8027 &env->src_rq->cfs_tasks, se.group_node) {
8028 if (!can_migrate_task(p, env))
8029 continue;
8030
8031 detach_task(p, env);
8032
8033 /*
8034 * Right now, this is only the second place where
8035 * lb_gained[env->idle] is updated (other is detach_tasks)
8036 * so we can safely collect stats here rather than
8037 * inside detach_tasks().
8038 */
8039 schedstat_inc(env->sd->lb_gained[env->idle]);
8040 return p;
8041 }
8042 return NULL;
8043 }
8044
8045 static const unsigned int sched_nr_migrate_break = 32;
8046
8047 /*
8048 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from
8049 * busiest_rq, as part of a balancing operation within domain "sd".
8050 *
8051 * Returns number of detached tasks if successful and 0 otherwise.
8052 */
detach_tasks(struct lb_env * env)8053 static int detach_tasks(struct lb_env *env)
8054 {
8055 struct list_head *tasks = &env->src_rq->cfs_tasks;
8056 unsigned long util, load;
8057 struct task_struct *p;
8058 int detached = 0;
8059 #ifdef CONFIG_SCHED_RTG
8060 int orig_loop = env->loop;
8061 #endif
8062
8063 lockdep_assert_held(&env->src_rq->lock);
8064
8065 if (env->imbalance <= 0)
8066 return 0;
8067
8068 #ifdef CONFIG_SCHED_RTG
8069 if (!same_cluster(env->dst_cpu, env->src_cpu))
8070 env->flags |= LBF_IGNORE_PREFERRED_CLUSTER_TASKS;
8071
8072 redo:
8073 #endif
8074 while (!list_empty(tasks)) {
8075 /*
8076 * We don't want to steal all, otherwise we may be treated likewise,
8077 * which could at worst lead to a livelock crash.
8078 */
8079 if (env->idle != CPU_NOT_IDLE && env->src_rq->nr_running <= 1)
8080 break;
8081
8082 p = list_last_entry(tasks, struct task_struct, se.group_node);
8083
8084 env->loop++;
8085 /* We've more or less seen every task there is, call it quits */
8086 if (env->loop > env->loop_max)
8087 break;
8088
8089 /* take a breather every nr_migrate tasks */
8090 if (env->loop > env->loop_break) {
8091 env->loop_break += sched_nr_migrate_break;
8092 env->flags |= LBF_NEED_BREAK;
8093 break;
8094 }
8095
8096 if (!can_migrate_task(p, env))
8097 goto next;
8098
8099 switch (env->migration_type) {
8100 case migrate_load:
8101 /*
8102 * Depending of the number of CPUs and tasks and the
8103 * cgroup hierarchy, task_h_load() can return a null
8104 * value. Make sure that env->imbalance decreases
8105 * otherwise detach_tasks() will stop only after
8106 * detaching up to loop_max tasks.
8107 */
8108 load = max_t(unsigned long, task_h_load(p), 1);
8109
8110 if (sched_feat(LB_MIN) &&
8111 load < 16 && !env->sd->nr_balance_failed)
8112 goto next;
8113
8114 /*
8115 * Make sure that we don't migrate too much load.
8116 * Nevertheless, let relax the constraint if
8117 * scheduler fails to find a good waiting task to
8118 * migrate.
8119 */
8120 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance)
8121 goto next;
8122
8123 env->imbalance -= load;
8124 break;
8125
8126 case migrate_util:
8127 util = task_util_est(p);
8128
8129 if (util > env->imbalance)
8130 goto next;
8131
8132 env->imbalance -= util;
8133 break;
8134
8135 case migrate_task:
8136 env->imbalance--;
8137 break;
8138
8139 case migrate_misfit:
8140 /* This is not a misfit task */
8141 if (task_fits_capacity(p, capacity_of(env->src_cpu)))
8142 goto next;
8143
8144 env->imbalance = 0;
8145 break;
8146 }
8147
8148 detach_task(p, env);
8149 list_add(&p->se.group_node, &env->tasks);
8150
8151 detached++;
8152
8153 #ifdef CONFIG_PREEMPTION
8154 /*
8155 * NEWIDLE balancing is a source of latency, so preemptible
8156 * kernels will stop after the first task is detached to minimize
8157 * the critical section.
8158 */
8159 if (env->idle == CPU_NEWLY_IDLE)
8160 break;
8161 #endif
8162
8163 /*
8164 * We only want to steal up to the prescribed amount of
8165 * load/util/tasks.
8166 */
8167 if (env->imbalance <= 0)
8168 break;
8169
8170 continue;
8171 next:
8172 list_move(&p->se.group_node, tasks);
8173 }
8174
8175 #ifdef CONFIG_SCHED_RTG
8176 if (env->flags & LBF_IGNORE_PREFERRED_CLUSTER_TASKS && !detached) {
8177 tasks = &env->src_rq->cfs_tasks;
8178 env->flags &= ~LBF_IGNORE_PREFERRED_CLUSTER_TASKS;
8179 env->loop = orig_loop;
8180 goto redo;
8181 }
8182 #endif
8183
8184 /*
8185 * Right now, this is one of only two places we collect this stat
8186 * so we can safely collect detach_one_task() stats here rather
8187 * than inside detach_one_task().
8188 */
8189 schedstat_add(env->sd->lb_gained[env->idle], detached);
8190
8191 return detached;
8192 }
8193
8194 /*
8195 * attach_task() -- attach the task detached by detach_task() to its new rq.
8196 */
attach_task(struct rq * rq,struct task_struct * p)8197 static void attach_task(struct rq *rq, struct task_struct *p)
8198 {
8199 lockdep_assert_held(&rq->lock);
8200
8201 BUG_ON(task_rq(p) != rq);
8202 activate_task(rq, p, ENQUEUE_NOCLOCK);
8203 check_preempt_curr(rq, p, 0);
8204 }
8205
8206 /*
8207 * attach_one_task() -- attaches the task returned from detach_one_task() to
8208 * its new rq.
8209 */
attach_one_task(struct rq * rq,struct task_struct * p)8210 static void attach_one_task(struct rq *rq, struct task_struct *p)
8211 {
8212 struct rq_flags rf;
8213
8214 rq_lock(rq, &rf);
8215 update_rq_clock(rq);
8216 attach_task(rq, p);
8217 rq_unlock(rq, &rf);
8218 }
8219
8220 /*
8221 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
8222 * new rq.
8223 */
attach_tasks(struct lb_env * env)8224 static void attach_tasks(struct lb_env *env)
8225 {
8226 struct list_head *tasks = &env->tasks;
8227 struct task_struct *p;
8228 struct rq_flags rf;
8229
8230 rq_lock(env->dst_rq, &rf);
8231 update_rq_clock(env->dst_rq);
8232
8233 while (!list_empty(tasks)) {
8234 p = list_first_entry(tasks, struct task_struct, se.group_node);
8235 list_del_init(&p->se.group_node);
8236
8237 attach_task(env->dst_rq, p);
8238 }
8239
8240 rq_unlock(env->dst_rq, &rf);
8241 }
8242
8243 #ifdef CONFIG_NO_HZ_COMMON
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)8244 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq)
8245 {
8246 if (cfs_rq->avg.load_avg)
8247 return true;
8248
8249 if (cfs_rq->avg.util_avg)
8250 return true;
8251
8252 return false;
8253 }
8254
others_have_blocked(struct rq * rq)8255 static inline bool others_have_blocked(struct rq *rq)
8256 {
8257 if (READ_ONCE(rq->avg_rt.util_avg))
8258 return true;
8259
8260 if (READ_ONCE(rq->avg_dl.util_avg))
8261 return true;
8262
8263 if (thermal_load_avg(rq))
8264 return true;
8265
8266 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
8267 if (READ_ONCE(rq->avg_irq.util_avg))
8268 return true;
8269 #endif
8270
8271 return false;
8272 }
8273
update_blocked_load_status(struct rq * rq,bool has_blocked)8274 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked)
8275 {
8276 rq->last_blocked_load_update_tick = jiffies;
8277
8278 if (!has_blocked)
8279 rq->has_blocked_load = 0;
8280 }
8281 #else
cfs_rq_has_blocked(struct cfs_rq * cfs_rq)8282 static inline bool cfs_rq_has_blocked(struct cfs_rq *cfs_rq) { return false; }
others_have_blocked(struct rq * rq)8283 static inline bool others_have_blocked(struct rq *rq) { return false; }
update_blocked_load_status(struct rq * rq,bool has_blocked)8284 static inline void update_blocked_load_status(struct rq *rq, bool has_blocked) {}
8285 #endif
8286
__update_blocked_others(struct rq * rq,bool * done)8287 static bool __update_blocked_others(struct rq *rq, bool *done)
8288 {
8289 const struct sched_class *curr_class;
8290 u64 now = rq_clock_pelt(rq);
8291 unsigned long thermal_pressure;
8292 bool decayed;
8293
8294 /*
8295 * update_load_avg() can call cpufreq_update_util(). Make sure that RT,
8296 * DL and IRQ signals have been updated before updating CFS.
8297 */
8298 curr_class = rq->curr->sched_class;
8299
8300 thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
8301
8302 decayed = update_rt_rq_load_avg(now, rq, curr_class == &rt_sched_class) |
8303 update_dl_rq_load_avg(now, rq, curr_class == &dl_sched_class) |
8304 update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure) |
8305 update_irq_load_avg(rq, 0);
8306
8307 if (others_have_blocked(rq))
8308 *done = false;
8309
8310 return decayed;
8311 }
8312
8313 #ifdef CONFIG_FAIR_GROUP_SCHED
8314
cfs_rq_is_decayed(struct cfs_rq * cfs_rq)8315 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq)
8316 {
8317 if (cfs_rq->load.weight)
8318 return false;
8319
8320 if (cfs_rq->avg.load_sum)
8321 return false;
8322
8323 if (cfs_rq->avg.util_sum)
8324 return false;
8325
8326 if (cfs_rq->avg.runnable_sum)
8327 return false;
8328
8329 return true;
8330 }
8331
__update_blocked_fair(struct rq * rq,bool * done)8332 static bool __update_blocked_fair(struct rq *rq, bool *done)
8333 {
8334 struct cfs_rq *cfs_rq, *pos;
8335 bool decayed = false;
8336 int cpu = cpu_of(rq);
8337
8338 /*
8339 * Iterates the task_group tree in a bottom up fashion, see
8340 * list_add_leaf_cfs_rq() for details.
8341 */
8342 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
8343 struct sched_entity *se;
8344
8345 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) {
8346 update_tg_load_avg(cfs_rq);
8347
8348 if (cfs_rq == &rq->cfs)
8349 decayed = true;
8350 }
8351
8352 /* Propagate pending load changes to the parent, if any: */
8353 se = cfs_rq->tg->se[cpu];
8354 if (se && !skip_blocked_update(se))
8355 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
8356
8357 /*
8358 * There can be a lot of idle CPU cgroups. Don't let fully
8359 * decayed cfs_rqs linger on the list.
8360 */
8361 if (cfs_rq_is_decayed(cfs_rq))
8362 list_del_leaf_cfs_rq(cfs_rq);
8363
8364 /* Don't need periodic decay once load/util_avg are null */
8365 if (cfs_rq_has_blocked(cfs_rq))
8366 *done = false;
8367 }
8368
8369 return decayed;
8370 }
8371
8372 /*
8373 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
8374 * This needs to be done in a top-down fashion because the load of a child
8375 * group is a fraction of its parents load.
8376 */
update_cfs_rq_h_load(struct cfs_rq * cfs_rq)8377 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
8378 {
8379 struct rq *rq = rq_of(cfs_rq);
8380 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
8381 unsigned long now = jiffies;
8382 unsigned long load;
8383
8384 if (cfs_rq->last_h_load_update == now)
8385 return;
8386
8387 WRITE_ONCE(cfs_rq->h_load_next, NULL);
8388 for_each_sched_entity(se) {
8389 cfs_rq = cfs_rq_of(se);
8390 WRITE_ONCE(cfs_rq->h_load_next, se);
8391 if (cfs_rq->last_h_load_update == now)
8392 break;
8393 }
8394
8395 if (!se) {
8396 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq);
8397 cfs_rq->last_h_load_update = now;
8398 }
8399
8400 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) {
8401 load = cfs_rq->h_load;
8402 load = div64_ul(load * se->avg.load_avg,
8403 cfs_rq_load_avg(cfs_rq) + 1);
8404 cfs_rq = group_cfs_rq(se);
8405 cfs_rq->h_load = load;
8406 cfs_rq->last_h_load_update = now;
8407 }
8408 }
8409
task_h_load(struct task_struct * p)8410 static unsigned long task_h_load(struct task_struct *p)
8411 {
8412 struct cfs_rq *cfs_rq = task_cfs_rq(p);
8413
8414 update_cfs_rq_h_load(cfs_rq);
8415 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load,
8416 cfs_rq_load_avg(cfs_rq) + 1);
8417 }
8418 #else
__update_blocked_fair(struct rq * rq,bool * done)8419 static bool __update_blocked_fair(struct rq *rq, bool *done)
8420 {
8421 struct cfs_rq *cfs_rq = &rq->cfs;
8422 bool decayed;
8423
8424 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq);
8425 if (cfs_rq_has_blocked(cfs_rq))
8426 *done = false;
8427
8428 return decayed;
8429 }
8430
task_h_load(struct task_struct * p)8431 static unsigned long task_h_load(struct task_struct *p)
8432 {
8433 return p->se.avg.load_avg;
8434 }
8435 #endif
8436
update_blocked_averages(int cpu)8437 static void update_blocked_averages(int cpu)
8438 {
8439 bool decayed = false, done = true;
8440 struct rq *rq = cpu_rq(cpu);
8441 struct rq_flags rf;
8442
8443 rq_lock_irqsave(rq, &rf);
8444 update_rq_clock(rq);
8445
8446 decayed |= __update_blocked_others(rq, &done);
8447 decayed |= __update_blocked_fair(rq, &done);
8448
8449 update_blocked_load_status(rq, !done);
8450 if (decayed)
8451 cpufreq_update_util(rq, 0);
8452 rq_unlock_irqrestore(rq, &rf);
8453 }
8454
8455 /********** Helpers for find_busiest_group ************************/
8456
8457 /*
8458 * sg_lb_stats - stats of a sched_group required for load_balancing
8459 */
8460 struct sg_lb_stats {
8461 unsigned long avg_load; /*Avg load across the CPUs of the group */
8462 unsigned long group_load; /* Total load over the CPUs of the group */
8463 unsigned long group_capacity;
8464 unsigned long group_util; /* Total utilization over the CPUs of the group */
8465 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */
8466 unsigned int sum_nr_running; /* Nr of tasks running in the group */
8467 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */
8468 unsigned int idle_cpus;
8469 unsigned int group_weight;
8470 enum group_type group_type;
8471 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */
8472 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */
8473 #ifdef CONFIG_NUMA_BALANCING
8474 unsigned int nr_numa_running;
8475 unsigned int nr_preferred_running;
8476 #endif
8477 };
8478
8479 /*
8480 * sd_lb_stats - Structure to store the statistics of a sched_domain
8481 * during load balancing.
8482 */
8483 struct sd_lb_stats {
8484 struct sched_group *busiest; /* Busiest group in this sd */
8485 struct sched_group *local; /* Local group in this sd */
8486 unsigned long total_load; /* Total load of all groups in sd */
8487 unsigned long total_capacity; /* Total capacity of all groups in sd */
8488 unsigned long avg_load; /* Average load across all groups in sd */
8489 unsigned int prefer_sibling; /* tasks should go to sibling first */
8490
8491 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
8492 struct sg_lb_stats local_stat; /* Statistics of the local group */
8493 };
8494
init_sd_lb_stats(struct sd_lb_stats * sds)8495 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
8496 {
8497 /*
8498 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
8499 * local_stat because update_sg_lb_stats() does a full clear/assignment.
8500 * We must however set busiest_stat::group_type and
8501 * busiest_stat::idle_cpus to the worst busiest group because
8502 * update_sd_pick_busiest() reads these before assignment.
8503 */
8504 *sds = (struct sd_lb_stats){
8505 .busiest = NULL,
8506 .local = NULL,
8507 .total_load = 0UL,
8508 .total_capacity = 0UL,
8509 .busiest_stat = {
8510 .idle_cpus = UINT_MAX,
8511 .group_type = group_has_spare,
8512 },
8513 };
8514 }
8515
scale_rt_capacity(int cpu)8516 static unsigned long scale_rt_capacity(int cpu)
8517 {
8518 struct rq *rq = cpu_rq(cpu);
8519 unsigned long max = arch_scale_cpu_capacity(cpu);
8520 unsigned long used, free;
8521 unsigned long irq;
8522
8523 irq = cpu_util_irq(rq);
8524
8525 if (unlikely(irq >= max))
8526 return 1;
8527
8528 /*
8529 * avg_rt.util_avg and avg_dl.util_avg track binary signals
8530 * (running and not running) with weights 0 and 1024 respectively.
8531 * avg_thermal.load_avg tracks thermal pressure and the weighted
8532 * average uses the actual delta max capacity(load).
8533 */
8534 used = READ_ONCE(rq->avg_rt.util_avg);
8535 used += READ_ONCE(rq->avg_dl.util_avg);
8536 used += thermal_load_avg(rq);
8537
8538 if (unlikely(used >= max))
8539 return 1;
8540
8541 free = max - used;
8542
8543 return scale_irq_capacity(free, irq, max);
8544 }
8545
update_cpu_capacity(struct sched_domain * sd,int cpu)8546 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
8547 {
8548 unsigned long capacity = scale_rt_capacity(cpu);
8549 struct sched_group *sdg = sd->groups;
8550
8551 cpu_rq(cpu)->cpu_capacity_orig = arch_scale_cpu_capacity(cpu);
8552
8553 if (!capacity)
8554 capacity = 1;
8555
8556 cpu_rq(cpu)->cpu_capacity = capacity;
8557 trace_sched_cpu_capacity_tp(cpu_rq(cpu));
8558
8559 sdg->sgc->capacity = capacity;
8560 sdg->sgc->min_capacity = capacity;
8561 sdg->sgc->max_capacity = capacity;
8562 }
8563
update_group_capacity(struct sched_domain * sd,int cpu)8564 void update_group_capacity(struct sched_domain *sd, int cpu)
8565 {
8566 struct sched_domain *child = sd->child;
8567 struct sched_group *group, *sdg = sd->groups;
8568 unsigned long capacity, min_capacity, max_capacity;
8569 unsigned long interval;
8570
8571 interval = msecs_to_jiffies(sd->balance_interval);
8572 interval = clamp(interval, 1UL, max_load_balance_interval);
8573 sdg->sgc->next_update = jiffies + interval;
8574
8575 if (!child) {
8576 update_cpu_capacity(sd, cpu);
8577 return;
8578 }
8579
8580 capacity = 0;
8581 min_capacity = ULONG_MAX;
8582 max_capacity = 0;
8583
8584 if (child->flags & SD_OVERLAP) {
8585 /*
8586 * SD_OVERLAP domains cannot assume that child groups
8587 * span the current group.
8588 */
8589
8590 for_each_cpu(cpu, sched_group_span(sdg)) {
8591 unsigned long cpu_cap = capacity_of(cpu);
8592
8593 if (cpu_isolated(cpu))
8594 continue;
8595
8596 capacity += cpu_cap;
8597 min_capacity = min(cpu_cap, min_capacity);
8598 max_capacity = max(cpu_cap, max_capacity);
8599 }
8600 } else {
8601 /*
8602 * !SD_OVERLAP domains can assume that child groups
8603 * span the current group.
8604 */
8605
8606 group = child->groups;
8607 do {
8608 struct sched_group_capacity *sgc = group->sgc;
8609 __maybe_unused cpumask_t *cpus =
8610 sched_group_span(group);
8611
8612 if (!cpu_isolated(cpumask_first(cpus))) {
8613 capacity += sgc->capacity;
8614 min_capacity = min(sgc->min_capacity,
8615 min_capacity);
8616 max_capacity = max(sgc->max_capacity,
8617 max_capacity);
8618 }
8619 group = group->next;
8620 } while (group != child->groups);
8621 }
8622
8623 sdg->sgc->capacity = capacity;
8624 sdg->sgc->min_capacity = min_capacity;
8625 sdg->sgc->max_capacity = max_capacity;
8626 }
8627
8628 /*
8629 * Check whether the capacity of the rq has been noticeably reduced by side
8630 * activity. The imbalance_pct is used for the threshold.
8631 * Return true is the capacity is reduced
8632 */
8633 static inline int
check_cpu_capacity(struct rq * rq,struct sched_domain * sd)8634 check_cpu_capacity(struct rq *rq, struct sched_domain *sd)
8635 {
8636 return ((rq->cpu_capacity * sd->imbalance_pct) <
8637 (rq->cpu_capacity_orig * 100));
8638 }
8639
8640 /*
8641 * Check whether a rq has a misfit task and if it looks like we can actually
8642 * help that task: we can migrate the task to a CPU of higher capacity, or
8643 * the task's current CPU is heavily pressured.
8644 */
check_misfit_status(struct rq * rq,struct sched_domain * sd)8645 static inline int check_misfit_status(struct rq *rq, struct sched_domain *sd)
8646 {
8647 return rq->misfit_task_load &&
8648 (rq->cpu_capacity_orig < rq->rd->max_cpu_capacity ||
8649 check_cpu_capacity(rq, sd));
8650 }
8651
8652 /*
8653 * Group imbalance indicates (and tries to solve) the problem where balancing
8654 * groups is inadequate due to ->cpus_ptr constraints.
8655 *
8656 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a
8657 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group.
8658 * Something like:
8659 *
8660 * { 0 1 2 3 } { 4 5 6 7 }
8661 * * * * *
8662 *
8663 * If we were to balance group-wise we'd place two tasks in the first group and
8664 * two tasks in the second group. Clearly this is undesired as it will overload
8665 * cpu 3 and leave one of the CPUs in the second group unused.
8666 *
8667 * The current solution to this issue is detecting the skew in the first group
8668 * by noticing the lower domain failed to reach balance and had difficulty
8669 * moving tasks due to affinity constraints.
8670 *
8671 * When this is so detected; this group becomes a candidate for busiest; see
8672 * update_sd_pick_busiest(). And calculate_imbalance() and
8673 * find_busiest_group() avoid some of the usual balance conditions to allow it
8674 * to create an effective group imbalance.
8675 *
8676 * This is a somewhat tricky proposition since the next run might not find the
8677 * group imbalance and decide the groups need to be balanced again. A most
8678 * subtle and fragile situation.
8679 */
8680
sg_imbalanced(struct sched_group * group)8681 static inline int sg_imbalanced(struct sched_group *group)
8682 {
8683 return group->sgc->imbalance;
8684 }
8685
8686 /*
8687 * group_has_capacity returns true if the group has spare capacity that could
8688 * be used by some tasks.
8689 * We consider that a group has spare capacity if the * number of task is
8690 * smaller than the number of CPUs or if the utilization is lower than the
8691 * available capacity for CFS tasks.
8692 * For the latter, we use a threshold to stabilize the state, to take into
8693 * account the variance of the tasks' load and to return true if the available
8694 * capacity in meaningful for the load balancer.
8695 * As an example, an available capacity of 1% can appear but it doesn't make
8696 * any benefit for the load balance.
8697 */
8698 static inline bool
group_has_capacity(unsigned int imbalance_pct,struct sg_lb_stats * sgs)8699 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
8700 {
8701 if (sgs->sum_nr_running < sgs->group_weight)
8702 return true;
8703
8704 if ((sgs->group_capacity * imbalance_pct) <
8705 (sgs->group_runnable * 100))
8706 return false;
8707
8708 if ((sgs->group_capacity * 100) >
8709 (sgs->group_util * imbalance_pct))
8710 return true;
8711
8712 return false;
8713 }
8714
8715 /*
8716 * group_is_overloaded returns true if the group has more tasks than it can
8717 * handle.
8718 * group_is_overloaded is not equals to !group_has_capacity because a group
8719 * with the exact right number of tasks, has no more spare capacity but is not
8720 * overloaded so both group_has_capacity and group_is_overloaded return
8721 * false.
8722 */
8723 static inline bool
group_is_overloaded(unsigned int imbalance_pct,struct sg_lb_stats * sgs)8724 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs)
8725 {
8726 if (sgs->sum_nr_running <= sgs->group_weight)
8727 return false;
8728
8729 if ((sgs->group_capacity * 100) <
8730 (sgs->group_util * imbalance_pct))
8731 return true;
8732
8733 if ((sgs->group_capacity * imbalance_pct) <
8734 (sgs->group_runnable * 100))
8735 return true;
8736
8737 return false;
8738 }
8739
8740 /*
8741 * group_smaller_min_cpu_capacity: Returns true if sched_group sg has smaller
8742 * per-CPU capacity than sched_group ref.
8743 */
8744 static inline bool
group_smaller_min_cpu_capacity(struct sched_group * sg,struct sched_group * ref)8745 group_smaller_min_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8746 {
8747 return fits_capacity(sg->sgc->min_capacity, ref->sgc->min_capacity);
8748 }
8749
8750 /*
8751 * group_smaller_max_cpu_capacity: Returns true if sched_group sg has smaller
8752 * per-CPU capacity_orig than sched_group ref.
8753 */
8754 static inline bool
group_smaller_max_cpu_capacity(struct sched_group * sg,struct sched_group * ref)8755 group_smaller_max_cpu_capacity(struct sched_group *sg, struct sched_group *ref)
8756 {
8757 return fits_capacity(sg->sgc->max_capacity, ref->sgc->max_capacity);
8758 }
8759
8760 static inline enum
group_classify(unsigned int imbalance_pct,struct sched_group * group,struct sg_lb_stats * sgs)8761 group_type group_classify(unsigned int imbalance_pct,
8762 struct sched_group *group,
8763 struct sg_lb_stats *sgs)
8764 {
8765 if (group_is_overloaded(imbalance_pct, sgs))
8766 return group_overloaded;
8767
8768 if (sg_imbalanced(group))
8769 return group_imbalanced;
8770
8771 if (sgs->group_asym_packing)
8772 return group_asym_packing;
8773
8774 if (sgs->group_misfit_task_load)
8775 return group_misfit_task;
8776
8777 if (!group_has_capacity(imbalance_pct, sgs))
8778 return group_fully_busy;
8779
8780 return group_has_spare;
8781 }
8782
update_nohz_stats(struct rq * rq,bool force)8783 static bool update_nohz_stats(struct rq *rq, bool force)
8784 {
8785 #ifdef CONFIG_NO_HZ_COMMON
8786 unsigned int cpu = rq->cpu;
8787
8788 if (!rq->has_blocked_load)
8789 return false;
8790
8791 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
8792 return false;
8793
8794 if (!force && !time_after(jiffies, rq->last_blocked_load_update_tick))
8795 return true;
8796
8797 update_blocked_averages(cpu);
8798
8799 return rq->has_blocked_load;
8800 #else
8801 return false;
8802 #endif
8803 }
8804
8805 /**
8806 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
8807 * @env: The load balancing environment.
8808 * @group: sched_group whose statistics are to be updated.
8809 * @sgs: variable to hold the statistics for this group.
8810 * @sg_status: Holds flag indicating the status of the sched_group
8811 */
update_sg_lb_stats(struct lb_env * env,struct sched_group * group,struct sg_lb_stats * sgs,int * sg_status)8812 static inline void update_sg_lb_stats(struct lb_env *env,
8813 struct sched_group *group,
8814 struct sg_lb_stats *sgs,
8815 int *sg_status)
8816 {
8817 int i, nr_running, local_group;
8818
8819 memset(sgs, 0, sizeof(*sgs));
8820
8821 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(group));
8822
8823 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
8824 struct rq *rq = cpu_rq(i);
8825
8826 if (cpu_isolated(i))
8827 continue;
8828
8829 if ((env->flags & LBF_NOHZ_STATS) && update_nohz_stats(rq, false))
8830 env->flags |= LBF_NOHZ_AGAIN;
8831
8832 sgs->group_load += cpu_load(rq);
8833 sgs->group_util += cpu_util(i);
8834 sgs->group_runnable += cpu_runnable(rq);
8835 sgs->sum_h_nr_running += rq->cfs.h_nr_running;
8836
8837 nr_running = rq->nr_running;
8838 sgs->sum_nr_running += nr_running;
8839
8840 if (nr_running > 1)
8841 *sg_status |= SG_OVERLOAD;
8842
8843 if (cpu_overutilized(i))
8844 *sg_status |= SG_OVERUTILIZED;
8845
8846 #ifdef CONFIG_NUMA_BALANCING
8847 sgs->nr_numa_running += rq->nr_numa_running;
8848 sgs->nr_preferred_running += rq->nr_preferred_running;
8849 #endif
8850 /*
8851 * No need to call idle_cpu() if nr_running is not 0
8852 */
8853 if (!nr_running && idle_cpu(i)) {
8854 sgs->idle_cpus++;
8855 /* Idle cpu can't have misfit task */
8856 continue;
8857 }
8858
8859 if (local_group)
8860 continue;
8861
8862 /* Check for a misfit task on the cpu */
8863 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
8864 sgs->group_misfit_task_load < rq->misfit_task_load) {
8865 sgs->group_misfit_task_load = rq->misfit_task_load;
8866 *sg_status |= SG_OVERLOAD;
8867 }
8868 }
8869
8870 /* Isolated CPU has no weight */
8871 if (!group->group_weight) {
8872 sgs->group_capacity = 0;
8873 sgs->avg_load = 0;
8874 sgs->group_type = group_has_spare;
8875 sgs->group_weight = group->group_weight;
8876 return;
8877 }
8878
8879 /* Check if dst CPU is idle and preferred to this group */
8880 if (env->sd->flags & SD_ASYM_PACKING &&
8881 env->idle != CPU_NOT_IDLE &&
8882 sgs->sum_h_nr_running &&
8883 sched_asym_prefer(env->dst_cpu, group->asym_prefer_cpu)) {
8884 sgs->group_asym_packing = 1;
8885 }
8886
8887 sgs->group_capacity = group->sgc->capacity;
8888
8889 sgs->group_weight = group->group_weight;
8890
8891 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs);
8892
8893 /* Computing avg_load makes sense only when group is overloaded */
8894 if (sgs->group_type == group_overloaded)
8895 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
8896 sgs->group_capacity;
8897 }
8898
8899 /**
8900 * update_sd_pick_busiest - return 1 on busiest group
8901 * @env: The load balancing environment.
8902 * @sds: sched_domain statistics
8903 * @sg: sched_group candidate to be checked for being the busiest
8904 * @sgs: sched_group statistics
8905 *
8906 * Determine if @sg is a busier group than the previously selected
8907 * busiest group.
8908 *
8909 * Return: %true if @sg is a busier group than the previously selected
8910 * busiest group. %false otherwise.
8911 */
update_sd_pick_busiest(struct lb_env * env,struct sd_lb_stats * sds,struct sched_group * sg,struct sg_lb_stats * sgs)8912 static bool update_sd_pick_busiest(struct lb_env *env,
8913 struct sd_lb_stats *sds,
8914 struct sched_group *sg,
8915 struct sg_lb_stats *sgs)
8916 {
8917 struct sg_lb_stats *busiest = &sds->busiest_stat;
8918
8919 /* Make sure that there is at least one task to pull */
8920 if (!sgs->sum_h_nr_running)
8921 return false;
8922
8923 /*
8924 * Don't try to pull misfit tasks we can't help.
8925 * We can use max_capacity here as reduction in capacity on some
8926 * CPUs in the group should either be possible to resolve
8927 * internally or be covered by avg_load imbalance (eventually).
8928 */
8929 if (sgs->group_type == group_misfit_task &&
8930 (!group_smaller_max_cpu_capacity(sg, sds->local) ||
8931 sds->local_stat.group_type != group_has_spare))
8932 return false;
8933
8934 if (sgs->group_type > busiest->group_type)
8935 return true;
8936
8937 if (sgs->group_type < busiest->group_type)
8938 return false;
8939
8940 /*
8941 * The candidate and the current busiest group are the same type of
8942 * group. Let check which one is the busiest according to the type.
8943 */
8944
8945 switch (sgs->group_type) {
8946 case group_overloaded:
8947 /* Select the overloaded group with highest avg_load. */
8948 if (sgs->avg_load <= busiest->avg_load)
8949 return false;
8950 break;
8951
8952 case group_imbalanced:
8953 /*
8954 * Select the 1st imbalanced group as we don't have any way to
8955 * choose one more than another.
8956 */
8957 return false;
8958
8959 case group_asym_packing:
8960 /* Prefer to move from lowest priority CPU's work */
8961 if (sched_asym_prefer(sg->asym_prefer_cpu, sds->busiest->asym_prefer_cpu))
8962 return false;
8963 break;
8964
8965 case group_misfit_task:
8966 /*
8967 * If we have more than one misfit sg go with the biggest
8968 * misfit.
8969 */
8970 if (sgs->group_misfit_task_load < busiest->group_misfit_task_load)
8971 return false;
8972 break;
8973
8974 case group_fully_busy:
8975 /*
8976 * Select the fully busy group with highest avg_load. In
8977 * theory, there is no need to pull task from such kind of
8978 * group because tasks have all compute capacity that they need
8979 * but we can still improve the overall throughput by reducing
8980 * contention when accessing shared HW resources.
8981 *
8982 * XXX for now avg_load is not computed and always 0 so we
8983 * select the 1st one.
8984 */
8985 if (sgs->avg_load <= busiest->avg_load)
8986 return false;
8987 break;
8988
8989 case group_has_spare:
8990 /*
8991 * Select not overloaded group with lowest number of idle cpus
8992 * and highest number of running tasks. We could also compare
8993 * the spare capacity which is more stable but it can end up
8994 * that the group has less spare capacity but finally more idle
8995 * CPUs which means less opportunity to pull tasks.
8996 */
8997 if (sgs->idle_cpus > busiest->idle_cpus)
8998 return false;
8999 else if ((sgs->idle_cpus == busiest->idle_cpus) &&
9000 (sgs->sum_nr_running <= busiest->sum_nr_running))
9001 return false;
9002
9003 break;
9004 }
9005
9006 /*
9007 * Candidate sg has no more than one task per CPU and has higher
9008 * per-CPU capacity. Migrating tasks to less capable CPUs may harm
9009 * throughput. Maximize throughput, power/energy consequences are not
9010 * considered.
9011 */
9012 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) &&
9013 (sgs->group_type <= group_fully_busy) &&
9014 (group_smaller_min_cpu_capacity(sds->local, sg)))
9015 return false;
9016
9017 return true;
9018 }
9019
9020 #ifdef CONFIG_NUMA_BALANCING
fbq_classify_group(struct sg_lb_stats * sgs)9021 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9022 {
9023 if (sgs->sum_h_nr_running > sgs->nr_numa_running)
9024 return regular;
9025 if (sgs->sum_h_nr_running > sgs->nr_preferred_running)
9026 return remote;
9027 return all;
9028 }
9029
fbq_classify_rq(struct rq * rq)9030 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9031 {
9032 if (rq->nr_running > rq->nr_numa_running)
9033 return regular;
9034 if (rq->nr_running > rq->nr_preferred_running)
9035 return remote;
9036 return all;
9037 }
9038 #else
fbq_classify_group(struct sg_lb_stats * sgs)9039 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
9040 {
9041 return all;
9042 }
9043
fbq_classify_rq(struct rq * rq)9044 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
9045 {
9046 return regular;
9047 }
9048 #endif /* CONFIG_NUMA_BALANCING */
9049
9050
9051 struct sg_lb_stats;
9052
9053 /*
9054 * task_running_on_cpu - return 1 if @p is running on @cpu.
9055 */
9056
task_running_on_cpu(int cpu,struct task_struct * p)9057 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p)
9058 {
9059 /* Task has no contribution or is new */
9060 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time))
9061 return 0;
9062
9063 if (task_on_rq_queued(p))
9064 return 1;
9065
9066 return 0;
9067 }
9068
9069 /**
9070 * idle_cpu_without - would a given CPU be idle without p ?
9071 * @cpu: the processor on which idleness is tested.
9072 * @p: task which should be ignored.
9073 *
9074 * Return: 1 if the CPU would be idle. 0 otherwise.
9075 */
idle_cpu_without(int cpu,struct task_struct * p)9076 static int idle_cpu_without(int cpu, struct task_struct *p)
9077 {
9078 struct rq *rq = cpu_rq(cpu);
9079
9080 if (rq->curr != rq->idle && rq->curr != p)
9081 return 0;
9082
9083 /*
9084 * rq->nr_running can't be used but an updated version without the
9085 * impact of p on cpu must be used instead. The updated nr_running
9086 * be computed and tested before calling idle_cpu_without().
9087 */
9088
9089 #ifdef CONFIG_SMP
9090 if (rq->ttwu_pending)
9091 return 0;
9092 #endif
9093
9094 return 1;
9095 }
9096
9097 /*
9098 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup.
9099 * @sd: The sched_domain level to look for idlest group.
9100 * @group: sched_group whose statistics are to be updated.
9101 * @sgs: variable to hold the statistics for this group.
9102 * @p: The task for which we look for the idlest group/CPU.
9103 */
update_sg_wakeup_stats(struct sched_domain * sd,struct sched_group * group,struct sg_lb_stats * sgs,struct task_struct * p)9104 static inline void update_sg_wakeup_stats(struct sched_domain *sd,
9105 struct sched_group *group,
9106 struct sg_lb_stats *sgs,
9107 struct task_struct *p)
9108 {
9109 int i, nr_running;
9110
9111 memset(sgs, 0, sizeof(*sgs));
9112
9113 for_each_cpu(i, sched_group_span(group)) {
9114 struct rq *rq = cpu_rq(i);
9115 unsigned int local;
9116
9117 sgs->group_load += cpu_load_without(rq, p);
9118 sgs->group_util += cpu_util_without(i, p);
9119 sgs->group_runnable += cpu_runnable_without(rq, p);
9120 local = task_running_on_cpu(i, p);
9121 sgs->sum_h_nr_running += rq->cfs.h_nr_running - local;
9122
9123 nr_running = rq->nr_running - local;
9124 sgs->sum_nr_running += nr_running;
9125
9126 /*
9127 * No need to call idle_cpu_without() if nr_running is not 0
9128 */
9129 if (!nr_running && idle_cpu_without(i, p))
9130 sgs->idle_cpus++;
9131
9132 }
9133
9134 /* Check if task fits in the group */
9135 if (sd->flags & SD_ASYM_CPUCAPACITY &&
9136 !task_fits_capacity(p, group->sgc->max_capacity)) {
9137 sgs->group_misfit_task_load = 1;
9138 }
9139
9140 sgs->group_capacity = group->sgc->capacity;
9141
9142 sgs->group_weight = group->group_weight;
9143
9144 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs);
9145
9146 /*
9147 * Computing avg_load makes sense only when group is fully busy or
9148 * overloaded
9149 */
9150 if (sgs->group_type == group_fully_busy ||
9151 sgs->group_type == group_overloaded)
9152 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) /
9153 sgs->group_capacity;
9154 }
9155
update_pick_idlest(struct sched_group * idlest,struct sg_lb_stats * idlest_sgs,struct sched_group * group,struct sg_lb_stats * sgs)9156 static bool update_pick_idlest(struct sched_group *idlest,
9157 struct sg_lb_stats *idlest_sgs,
9158 struct sched_group *group,
9159 struct sg_lb_stats *sgs)
9160 {
9161 if (sgs->group_type < idlest_sgs->group_type)
9162 return true;
9163
9164 if (sgs->group_type > idlest_sgs->group_type)
9165 return false;
9166
9167 /*
9168 * The candidate and the current idlest group are the same type of
9169 * group. Let check which one is the idlest according to the type.
9170 */
9171
9172 switch (sgs->group_type) {
9173 case group_overloaded:
9174 case group_fully_busy:
9175 /* Select the group with lowest avg_load. */
9176 if (idlest_sgs->avg_load <= sgs->avg_load)
9177 return false;
9178 break;
9179
9180 case group_imbalanced:
9181 case group_asym_packing:
9182 /* Those types are not used in the slow wakeup path */
9183 return false;
9184
9185 case group_misfit_task:
9186 /* Select group with the highest max capacity */
9187 if (idlest->sgc->max_capacity >= group->sgc->max_capacity)
9188 return false;
9189 break;
9190
9191 case group_has_spare:
9192 /* Select group with most idle CPUs */
9193 if (idlest_sgs->idle_cpus > sgs->idle_cpus)
9194 return false;
9195
9196 /* Select group with lowest group_util */
9197 if (idlest_sgs->idle_cpus == sgs->idle_cpus &&
9198 idlest_sgs->group_util <= sgs->group_util)
9199 return false;
9200
9201 break;
9202 }
9203
9204 return true;
9205 }
9206
9207 /*
9208 * find_idlest_group() finds and returns the least busy CPU group within the
9209 * domain.
9210 *
9211 * Assumes p is allowed on at least one CPU in sd.
9212 */
9213 static struct sched_group *
find_idlest_group(struct sched_domain * sd,struct task_struct * p,int this_cpu)9214 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
9215 {
9216 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups;
9217 struct sg_lb_stats local_sgs, tmp_sgs;
9218 struct sg_lb_stats *sgs;
9219 unsigned long imbalance;
9220 struct sg_lb_stats idlest_sgs = {
9221 .avg_load = UINT_MAX,
9222 .group_type = group_overloaded,
9223 };
9224 #ifdef CONFIG_CPU_ISOLATION_OPT
9225 cpumask_t allowed_cpus;
9226
9227 cpumask_andnot(&allowed_cpus, p->cpus_ptr, cpu_isolated_mask);
9228 #endif
9229
9230 imbalance = scale_load_down(NICE_0_LOAD) *
9231 (sd->imbalance_pct-100) / 100;
9232
9233 do {
9234 int local_group;
9235
9236 /* Skip over this group if it has no CPUs allowed */
9237 #ifdef CONFIG_CPU_ISOLATION_OPT
9238 if (!cpumask_intersects(sched_group_span(group),
9239 &allowed_cpus))
9240 #else
9241 if (!cpumask_intersects(sched_group_span(group),
9242 p->cpus_ptr))
9243 #endif
9244 continue;
9245
9246 local_group = cpumask_test_cpu(this_cpu,
9247 sched_group_span(group));
9248
9249 if (local_group) {
9250 sgs = &local_sgs;
9251 local = group;
9252 } else {
9253 sgs = &tmp_sgs;
9254 }
9255
9256 update_sg_wakeup_stats(sd, group, sgs, p);
9257
9258 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) {
9259 idlest = group;
9260 idlest_sgs = *sgs;
9261 }
9262
9263 } while (group = group->next, group != sd->groups);
9264
9265
9266 /* There is no idlest group to push tasks to */
9267 if (!idlest)
9268 return NULL;
9269
9270 /* The local group has been skipped because of CPU affinity */
9271 if (!local)
9272 return idlest;
9273
9274 /*
9275 * If the local group is idler than the selected idlest group
9276 * don't try and push the task.
9277 */
9278 if (local_sgs.group_type < idlest_sgs.group_type)
9279 return NULL;
9280
9281 /*
9282 * If the local group is busier than the selected idlest group
9283 * try and push the task.
9284 */
9285 if (local_sgs.group_type > idlest_sgs.group_type)
9286 return idlest;
9287
9288 switch (local_sgs.group_type) {
9289 case group_overloaded:
9290 case group_fully_busy:
9291 /*
9292 * When comparing groups across NUMA domains, it's possible for
9293 * the local domain to be very lightly loaded relative to the
9294 * remote domains but "imbalance" skews the comparison making
9295 * remote CPUs look much more favourable. When considering
9296 * cross-domain, add imbalance to the load on the remote node
9297 * and consider staying local.
9298 */
9299
9300 if ((sd->flags & SD_NUMA) &&
9301 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load))
9302 return NULL;
9303
9304 /*
9305 * If the local group is less loaded than the selected
9306 * idlest group don't try and push any tasks.
9307 */
9308 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance))
9309 return NULL;
9310
9311 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load)
9312 return NULL;
9313 break;
9314
9315 case group_imbalanced:
9316 case group_asym_packing:
9317 /* Those type are not used in the slow wakeup path */
9318 return NULL;
9319
9320 case group_misfit_task:
9321 /* Select group with the highest max capacity */
9322 if (local->sgc->max_capacity >= idlest->sgc->max_capacity)
9323 return NULL;
9324 break;
9325
9326 case group_has_spare:
9327 if (sd->flags & SD_NUMA) {
9328 #ifdef CONFIG_NUMA_BALANCING
9329 int idlest_cpu;
9330 /*
9331 * If there is spare capacity at NUMA, try to select
9332 * the preferred node
9333 */
9334 if (cpu_to_node(this_cpu) == p->numa_preferred_nid)
9335 return NULL;
9336
9337 idlest_cpu = cpumask_first(sched_group_span(idlest));
9338 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid)
9339 return idlest;
9340 #endif
9341 /*
9342 * Otherwise, keep the task on this node to stay close
9343 * its wakeup source and improve locality. If there is
9344 * a real need of migration, periodic load balance will
9345 * take care of it.
9346 */
9347 if (local_sgs.idle_cpus)
9348 return NULL;
9349 }
9350
9351 /*
9352 * Select group with highest number of idle CPUs. We could also
9353 * compare the utilization which is more stable but it can end
9354 * up that the group has less spare capacity but finally more
9355 * idle CPUs which means more opportunity to run task.
9356 */
9357 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus)
9358 return NULL;
9359 break;
9360 }
9361
9362 return idlest;
9363 }
9364
9365 /**
9366 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
9367 * @env: The load balancing environment.
9368 * @sds: variable to hold the statistics for this sched_domain.
9369 */
9370
update_sd_lb_stats(struct lb_env * env,struct sd_lb_stats * sds)9371 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
9372 {
9373 struct sched_domain *child = env->sd->child;
9374 struct sched_group *sg = env->sd->groups;
9375 struct sg_lb_stats *local = &sds->local_stat;
9376 struct sg_lb_stats tmp_sgs;
9377 int sg_status = 0;
9378
9379 #ifdef CONFIG_NO_HZ_COMMON
9380 if (env->idle == CPU_NEWLY_IDLE && READ_ONCE(nohz.has_blocked))
9381 env->flags |= LBF_NOHZ_STATS;
9382 #endif
9383
9384 do {
9385 struct sg_lb_stats *sgs = &tmp_sgs;
9386 int local_group;
9387
9388 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg));
9389 if (local_group) {
9390 sds->local = sg;
9391 sgs = local;
9392
9393 if (env->idle != CPU_NEWLY_IDLE ||
9394 time_after_eq(jiffies, sg->sgc->next_update))
9395 update_group_capacity(env->sd, env->dst_cpu);
9396 }
9397
9398 update_sg_lb_stats(env, sg, sgs, &sg_status);
9399
9400 if (local_group)
9401 goto next_group;
9402
9403
9404 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
9405 sds->busiest = sg;
9406 sds->busiest_stat = *sgs;
9407 }
9408
9409 next_group:
9410 /* Now, start updating sd_lb_stats */
9411 sds->total_load += sgs->group_load;
9412 sds->total_capacity += sgs->group_capacity;
9413
9414 sg = sg->next;
9415 } while (sg != env->sd->groups);
9416
9417 /* Tag domain that child domain prefers tasks go to siblings first */
9418 sds->prefer_sibling = child && child->flags & SD_PREFER_SIBLING;
9419
9420 #ifdef CONFIG_NO_HZ_COMMON
9421 if ((env->flags & LBF_NOHZ_AGAIN) &&
9422 cpumask_subset(nohz.idle_cpus_mask, sched_domain_span(env->sd))) {
9423
9424 WRITE_ONCE(nohz.next_blocked,
9425 jiffies + msecs_to_jiffies(LOAD_AVG_PERIOD));
9426 }
9427 #endif
9428
9429 if (env->sd->flags & SD_NUMA)
9430 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
9431
9432 if (!env->sd->parent) {
9433 struct root_domain *rd = env->dst_rq->rd;
9434
9435 /* update overload indicator if we are at root domain */
9436 WRITE_ONCE(rd->overload, sg_status & SG_OVERLOAD);
9437
9438 /* Update over-utilization (tipping point, U >= 0) indicator */
9439 WRITE_ONCE(rd->overutilized, sg_status & SG_OVERUTILIZED);
9440 trace_sched_overutilized_tp(rd, sg_status & SG_OVERUTILIZED);
9441 } else if (sg_status & SG_OVERUTILIZED) {
9442 struct root_domain *rd = env->dst_rq->rd;
9443
9444 WRITE_ONCE(rd->overutilized, SG_OVERUTILIZED);
9445 trace_sched_overutilized_tp(rd, SG_OVERUTILIZED);
9446 }
9447 }
9448
adjust_numa_imbalance(int imbalance,int nr_running)9449 static inline long adjust_numa_imbalance(int imbalance, int nr_running)
9450 {
9451 unsigned int imbalance_min;
9452
9453 /*
9454 * Allow a small imbalance based on a simple pair of communicating
9455 * tasks that remain local when the source domain is almost idle.
9456 */
9457 imbalance_min = 2;
9458 if (nr_running <= imbalance_min)
9459 return 0;
9460
9461 return imbalance;
9462 }
9463
9464 /**
9465 * calculate_imbalance - Calculate the amount of imbalance present within the
9466 * groups of a given sched_domain during load balance.
9467 * @env: load balance environment
9468 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
9469 */
calculate_imbalance(struct lb_env * env,struct sd_lb_stats * sds)9470 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
9471 {
9472 struct sg_lb_stats *local, *busiest;
9473
9474 local = &sds->local_stat;
9475 busiest = &sds->busiest_stat;
9476
9477 if (busiest->group_type == group_misfit_task) {
9478 /* Set imbalance to allow misfit tasks to be balanced. */
9479 env->migration_type = migrate_misfit;
9480 env->imbalance = 1;
9481 return;
9482 }
9483
9484 if (busiest->group_type == group_asym_packing) {
9485 /*
9486 * In case of asym capacity, we will try to migrate all load to
9487 * the preferred CPU.
9488 */
9489 env->migration_type = migrate_task;
9490 env->imbalance = busiest->sum_h_nr_running;
9491 return;
9492 }
9493
9494 if (busiest->group_type == group_imbalanced) {
9495 /*
9496 * In the group_imb case we cannot rely on group-wide averages
9497 * to ensure CPU-load equilibrium, try to move any task to fix
9498 * the imbalance. The next load balance will take care of
9499 * balancing back the system.
9500 */
9501 env->migration_type = migrate_task;
9502 env->imbalance = 1;
9503 return;
9504 }
9505
9506 /*
9507 * Try to use spare capacity of local group without overloading it or
9508 * emptying busiest.
9509 */
9510 if (local->group_type == group_has_spare) {
9511 if ((busiest->group_type > group_fully_busy) &&
9512 !(env->sd->flags & SD_SHARE_PKG_RESOURCES)) {
9513 /*
9514 * If busiest is overloaded, try to fill spare
9515 * capacity. This might end up creating spare capacity
9516 * in busiest or busiest still being overloaded but
9517 * there is no simple way to directly compute the
9518 * amount of load to migrate in order to balance the
9519 * system.
9520 */
9521 env->migration_type = migrate_util;
9522 env->imbalance = max(local->group_capacity, local->group_util) -
9523 local->group_util;
9524
9525 /*
9526 * In some cases, the group's utilization is max or even
9527 * higher than capacity because of migrations but the
9528 * local CPU is (newly) idle. There is at least one
9529 * waiting task in this overloaded busiest group. Let's
9530 * try to pull it.
9531 */
9532 if (env->idle != CPU_NOT_IDLE && env->imbalance == 0) {
9533 env->migration_type = migrate_task;
9534 env->imbalance = 1;
9535 }
9536
9537 return;
9538 }
9539
9540 if (busiest->group_weight == 1 || sds->prefer_sibling) {
9541 unsigned int nr_diff = busiest->sum_nr_running;
9542 /*
9543 * When prefer sibling, evenly spread running tasks on
9544 * groups.
9545 */
9546 env->migration_type = migrate_task;
9547 lsub_positive(&nr_diff, local->sum_nr_running);
9548 env->imbalance = nr_diff >> 1;
9549 } else {
9550
9551 /*
9552 * If there is no overload, we just want to even the number of
9553 * idle cpus.
9554 */
9555 env->migration_type = migrate_task;
9556 env->imbalance = max_t(long, 0, (local->idle_cpus -
9557 busiest->idle_cpus) >> 1);
9558 }
9559
9560 /* Consider allowing a small imbalance between NUMA groups */
9561 if (env->sd->flags & SD_NUMA)
9562 env->imbalance = adjust_numa_imbalance(env->imbalance,
9563 busiest->sum_nr_running);
9564
9565 return;
9566 }
9567
9568 /*
9569 * Local is fully busy but has to take more load to relieve the
9570 * busiest group
9571 */
9572 if (local->group_type < group_overloaded) {
9573 /*
9574 * Local will become overloaded so the avg_load metrics are
9575 * finally needed.
9576 */
9577
9578 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) /
9579 local->group_capacity;
9580
9581 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) /
9582 sds->total_capacity;
9583 /*
9584 * If the local group is more loaded than the selected
9585 * busiest group don't try to pull any tasks.
9586 */
9587 if (local->avg_load >= busiest->avg_load) {
9588 env->imbalance = 0;
9589 return;
9590 }
9591 }
9592
9593 /*
9594 * Both group are or will become overloaded and we're trying to get all
9595 * the CPUs to the average_load, so we don't want to push ourselves
9596 * above the average load, nor do we wish to reduce the max loaded CPU
9597 * below the average load. At the same time, we also don't want to
9598 * reduce the group load below the group capacity. Thus we look for
9599 * the minimum possible imbalance.
9600 */
9601 env->migration_type = migrate_load;
9602 env->imbalance = min(
9603 (busiest->avg_load - sds->avg_load) * busiest->group_capacity,
9604 (sds->avg_load - local->avg_load) * local->group_capacity
9605 ) / SCHED_CAPACITY_SCALE;
9606 }
9607
9608 /******* find_busiest_group() helpers end here *********************/
9609
9610 /*
9611 * Decision matrix according to the local and busiest group type:
9612 *
9613 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded
9614 * has_spare nr_idle balanced N/A N/A balanced balanced
9615 * fully_busy nr_idle nr_idle N/A N/A balanced balanced
9616 * misfit_task force N/A N/A N/A force force
9617 * asym_packing force force N/A N/A force force
9618 * imbalanced force force N/A N/A force force
9619 * overloaded force force N/A N/A force avg_load
9620 *
9621 * N/A : Not Applicable because already filtered while updating
9622 * statistics.
9623 * balanced : The system is balanced for these 2 groups.
9624 * force : Calculate the imbalance as load migration is probably needed.
9625 * avg_load : Only if imbalance is significant enough.
9626 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite
9627 * different in groups.
9628 */
9629
9630 /**
9631 * find_busiest_group - Returns the busiest group within the sched_domain
9632 * if there is an imbalance.
9633 *
9634 * Also calculates the amount of runnable load which should be moved
9635 * to restore balance.
9636 *
9637 * @env: The load balancing environment.
9638 *
9639 * Return: - The busiest group if imbalance exists.
9640 */
find_busiest_group(struct lb_env * env)9641 static struct sched_group *find_busiest_group(struct lb_env *env)
9642 {
9643 struct sg_lb_stats *local, *busiest;
9644 struct sd_lb_stats sds;
9645
9646 init_sd_lb_stats(&sds);
9647
9648 /*
9649 * Compute the various statistics relevant for load balancing at
9650 * this level.
9651 */
9652 update_sd_lb_stats(env, &sds);
9653
9654 if (sched_energy_enabled()) {
9655 struct root_domain *rd = env->dst_rq->rd;
9656
9657 if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized))
9658 goto out_balanced;
9659 }
9660
9661 local = &sds.local_stat;
9662 busiest = &sds.busiest_stat;
9663
9664 /* There is no busy sibling group to pull tasks from */
9665 if (!sds.busiest)
9666 goto out_balanced;
9667
9668 /* Misfit tasks should be dealt with regardless of the avg load */
9669 if (busiest->group_type == group_misfit_task)
9670 goto force_balance;
9671
9672 /* ASYM feature bypasses nice load balance check */
9673 if (busiest->group_type == group_asym_packing)
9674 goto force_balance;
9675
9676 /*
9677 * If the busiest group is imbalanced the below checks don't
9678 * work because they assume all things are equal, which typically
9679 * isn't true due to cpus_ptr constraints and the like.
9680 */
9681 if (busiest->group_type == group_imbalanced)
9682 goto force_balance;
9683
9684 /*
9685 * If the local group is busier than the selected busiest group
9686 * don't try and pull any tasks.
9687 */
9688 if (local->group_type > busiest->group_type)
9689 goto out_balanced;
9690
9691 /*
9692 * When groups are overloaded, use the avg_load to ensure fairness
9693 * between tasks.
9694 */
9695 if (local->group_type == group_overloaded) {
9696 /*
9697 * If the local group is more loaded than the selected
9698 * busiest group don't try to pull any tasks.
9699 */
9700 if (local->avg_load >= busiest->avg_load)
9701 goto out_balanced;
9702
9703 /* XXX broken for overlapping NUMA groups */
9704 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) /
9705 sds.total_capacity;
9706
9707 /*
9708 * Don't pull any tasks if this group is already above the
9709 * domain average load.
9710 */
9711 if (local->avg_load >= sds.avg_load)
9712 goto out_balanced;
9713
9714 /*
9715 * If the busiest group is more loaded, use imbalance_pct to be
9716 * conservative.
9717 */
9718 if (100 * busiest->avg_load <=
9719 env->sd->imbalance_pct * local->avg_load)
9720 goto out_balanced;
9721 }
9722
9723 /* Try to move all excess tasks to child's sibling domain */
9724 if (sds.prefer_sibling && local->group_type == group_has_spare &&
9725 busiest->sum_nr_running > local->sum_nr_running + 1)
9726 goto force_balance;
9727
9728 if (busiest->group_type != group_overloaded) {
9729 if (env->idle == CPU_NOT_IDLE)
9730 /*
9731 * If the busiest group is not overloaded (and as a
9732 * result the local one too) but this CPU is already
9733 * busy, let another idle CPU try to pull task.
9734 */
9735 goto out_balanced;
9736
9737 if (busiest->group_weight > 1 &&
9738 local->idle_cpus <= (busiest->idle_cpus + 1))
9739 /*
9740 * If the busiest group is not overloaded
9741 * and there is no imbalance between this and busiest
9742 * group wrt idle CPUs, it is balanced. The imbalance
9743 * becomes significant if the diff is greater than 1
9744 * otherwise we might end up to just move the imbalance
9745 * on another group. Of course this applies only if
9746 * there is more than 1 CPU per group.
9747 */
9748 goto out_balanced;
9749
9750 if (busiest->sum_h_nr_running == 1)
9751 /*
9752 * busiest doesn't have any tasks waiting to run
9753 */
9754 goto out_balanced;
9755 }
9756
9757 force_balance:
9758 /* Looks like there is an imbalance. Compute it */
9759 calculate_imbalance(env, &sds);
9760 return env->imbalance ? sds.busiest : NULL;
9761
9762 out_balanced:
9763 env->imbalance = 0;
9764 return NULL;
9765 }
9766
9767 /*
9768 * find_busiest_queue - find the busiest runqueue among the CPUs in the group.
9769 */
find_busiest_queue(struct lb_env * env,struct sched_group * group)9770 static struct rq *find_busiest_queue(struct lb_env *env,
9771 struct sched_group *group)
9772 {
9773 struct rq *busiest = NULL, *rq;
9774 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1;
9775 unsigned int busiest_nr = 0;
9776 int i;
9777
9778 for_each_cpu_and(i, sched_group_span(group), env->cpus) {
9779 unsigned long capacity, load, util;
9780 unsigned int nr_running;
9781 enum fbq_type rt;
9782
9783 rq = cpu_rq(i);
9784 rt = fbq_classify_rq(rq);
9785
9786 /*
9787 * We classify groups/runqueues into three groups:
9788 * - regular: there are !numa tasks
9789 * - remote: there are numa tasks that run on the 'wrong' node
9790 * - all: there is no distinction
9791 *
9792 * In order to avoid migrating ideally placed numa tasks,
9793 * ignore those when there's better options.
9794 *
9795 * If we ignore the actual busiest queue to migrate another
9796 * task, the next balance pass can still reduce the busiest
9797 * queue by moving tasks around inside the node.
9798 *
9799 * If we cannot move enough load due to this classification
9800 * the next pass will adjust the group classification and
9801 * allow migration of more tasks.
9802 *
9803 * Both cases only affect the total convergence complexity.
9804 */
9805 if (rt > env->fbq_type)
9806 continue;
9807
9808 if (cpu_isolated(i))
9809 continue;
9810
9811 capacity = capacity_of(i);
9812 nr_running = rq->cfs.h_nr_running;
9813
9814 /*
9815 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could
9816 * eventually lead to active_balancing high->low capacity.
9817 * Higher per-CPU capacity is considered better than balancing
9818 * average load.
9819 */
9820 if (env->sd->flags & SD_ASYM_CPUCAPACITY &&
9821 capacity_of(env->dst_cpu) < capacity &&
9822 nr_running == 1)
9823 continue;
9824
9825 switch (env->migration_type) {
9826 case migrate_load:
9827 /*
9828 * When comparing with load imbalance, use cpu_load()
9829 * which is not scaled with the CPU capacity.
9830 */
9831 load = cpu_load(rq);
9832
9833 if (nr_running == 1 && load > env->imbalance &&
9834 !check_cpu_capacity(rq, env->sd))
9835 break;
9836
9837 /*
9838 * For the load comparisons with the other CPUs,
9839 * consider the cpu_load() scaled with the CPU
9840 * capacity, so that the load can be moved away
9841 * from the CPU that is potentially running at a
9842 * lower capacity.
9843 *
9844 * Thus we're looking for max(load_i / capacity_i),
9845 * crosswise multiplication to rid ourselves of the
9846 * division works out to:
9847 * load_i * capacity_j > load_j * capacity_i;
9848 * where j is our previous maximum.
9849 */
9850 if (load * busiest_capacity > busiest_load * capacity) {
9851 busiest_load = load;
9852 busiest_capacity = capacity;
9853 busiest = rq;
9854 }
9855 break;
9856
9857 case migrate_util:
9858 util = cpu_util(cpu_of(rq));
9859
9860 /*
9861 * Don't try to pull utilization from a CPU with one
9862 * running task. Whatever its utilization, we will fail
9863 * detach the task.
9864 */
9865 if (nr_running <= 1)
9866 continue;
9867
9868 if (busiest_util < util) {
9869 busiest_util = util;
9870 busiest = rq;
9871 }
9872 break;
9873
9874 case migrate_task:
9875 if (busiest_nr < nr_running) {
9876 busiest_nr = nr_running;
9877 busiest = rq;
9878 }
9879 break;
9880
9881 case migrate_misfit:
9882 /*
9883 * For ASYM_CPUCAPACITY domains with misfit tasks we
9884 * simply seek the "biggest" misfit task.
9885 */
9886 if (rq->misfit_task_load > busiest_load) {
9887 busiest_load = rq->misfit_task_load;
9888 busiest = rq;
9889 }
9890
9891 break;
9892
9893 }
9894 }
9895
9896 return busiest;
9897 }
9898
9899 /*
9900 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
9901 * so long as it is large enough.
9902 */
9903 #define MAX_PINNED_INTERVAL 512
9904
9905 static inline bool
asym_active_balance(struct lb_env * env)9906 asym_active_balance(struct lb_env *env)
9907 {
9908 /*
9909 * ASYM_PACKING needs to force migrate tasks from busy but
9910 * lower priority CPUs in order to pack all tasks in the
9911 * highest priority CPUs.
9912 */
9913 return env->idle != CPU_NOT_IDLE && (env->sd->flags & SD_ASYM_PACKING) &&
9914 sched_asym_prefer(env->dst_cpu, env->src_cpu);
9915 }
9916
9917 static inline bool
voluntary_active_balance(struct lb_env * env)9918 voluntary_active_balance(struct lb_env *env)
9919 {
9920 struct sched_domain *sd = env->sd;
9921
9922 if (asym_active_balance(env))
9923 return 1;
9924
9925 /*
9926 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task.
9927 * It's worth migrating the task if the src_cpu's capacity is reduced
9928 * because of other sched_class or IRQs if more capacity stays
9929 * available on dst_cpu.
9930 */
9931 if ((env->idle != CPU_NOT_IDLE) &&
9932 (env->src_rq->cfs.h_nr_running == 1)) {
9933 if ((check_cpu_capacity(env->src_rq, sd)) &&
9934 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100))
9935 return 1;
9936 }
9937
9938 if (env->migration_type == migrate_misfit)
9939 return 1;
9940
9941 return 0;
9942 }
9943
need_active_balance(struct lb_env * env)9944 static int need_active_balance(struct lb_env *env)
9945 {
9946 struct sched_domain *sd = env->sd;
9947
9948 if (voluntary_active_balance(env))
9949 return 1;
9950
9951 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
9952 }
9953
9954 #ifdef CONFIG_CPU_ISOLATION_OPT
group_balance_cpu_not_isolated(struct sched_group * sg)9955 int group_balance_cpu_not_isolated(struct sched_group *sg)
9956 {
9957 cpumask_t cpus;
9958
9959 cpumask_and(&cpus, sched_group_span(sg), group_balance_mask(sg));
9960 cpumask_andnot(&cpus, &cpus, cpu_isolated_mask);
9961 return cpumask_first(&cpus);
9962 }
9963 #endif
9964
9965 static int active_load_balance_cpu_stop(void *data);
9966
should_we_balance(struct lb_env * env)9967 static int should_we_balance(struct lb_env *env)
9968 {
9969 struct sched_group *sg = env->sd->groups;
9970 int cpu;
9971
9972 /*
9973 * Ensure the balancing environment is consistent; can happen
9974 * when the softirq triggers 'during' hotplug.
9975 */
9976 if (!cpumask_test_cpu(env->dst_cpu, env->cpus))
9977 return 0;
9978
9979 /*
9980 * In the newly idle case, we will allow all the CPUs
9981 * to do the newly idle load balance.
9982 */
9983 if (env->idle == CPU_NEWLY_IDLE)
9984 return 1;
9985
9986 /* Try to find first idle CPU */
9987 for_each_cpu_and(cpu, group_balance_mask(sg), env->cpus) {
9988 if (!idle_cpu(cpu) || cpu_isolated(cpu))
9989 continue;
9990
9991 /* Are we the first idle CPU? */
9992 return cpu == env->dst_cpu;
9993 }
9994
9995 /* Are we the first CPU of this group ? */
9996 return group_balance_cpu_not_isolated(sg) == env->dst_cpu;
9997 }
9998
9999 /*
10000 * Check this_cpu to ensure it is balanced within domain. Attempt to move
10001 * tasks if there is an imbalance.
10002 */
load_balance(int this_cpu,struct rq * this_rq,struct sched_domain * sd,enum cpu_idle_type idle,int * continue_balancing)10003 static int load_balance(int this_cpu, struct rq *this_rq,
10004 struct sched_domain *sd, enum cpu_idle_type idle,
10005 int *continue_balancing)
10006 {
10007 int ld_moved, cur_ld_moved, active_balance = 0;
10008 struct sched_domain *sd_parent = sd->parent;
10009 struct sched_group *group;
10010 struct rq *busiest;
10011 struct rq_flags rf;
10012 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
10013
10014 struct lb_env env = {
10015 .sd = sd,
10016 .dst_cpu = this_cpu,
10017 .dst_rq = this_rq,
10018 .dst_grpmask = sched_group_span(sd->groups),
10019 .idle = idle,
10020 .loop_break = sched_nr_migrate_break,
10021 .cpus = cpus,
10022 .fbq_type = all,
10023 .tasks = LIST_HEAD_INIT(env.tasks),
10024 };
10025
10026 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask);
10027
10028 schedstat_inc(sd->lb_count[idle]);
10029
10030 redo:
10031 if (!should_we_balance(&env)) {
10032 *continue_balancing = 0;
10033 goto out_balanced;
10034 }
10035
10036 group = find_busiest_group(&env);
10037 if (!group) {
10038 schedstat_inc(sd->lb_nobusyg[idle]);
10039 goto out_balanced;
10040 }
10041
10042 busiest = find_busiest_queue(&env, group);
10043 if (!busiest) {
10044 schedstat_inc(sd->lb_nobusyq[idle]);
10045 goto out_balanced;
10046 }
10047
10048 BUG_ON(busiest == env.dst_rq);
10049
10050 schedstat_add(sd->lb_imbalance[idle], env.imbalance);
10051
10052 env.src_cpu = busiest->cpu;
10053 env.src_rq = busiest;
10054
10055 ld_moved = 0;
10056 if (busiest->nr_running > 1) {
10057 /*
10058 * Attempt to move tasks. If find_busiest_group has found
10059 * an imbalance but busiest->nr_running <= 1, the group is
10060 * still unbalanced. ld_moved simply stays zero, so it is
10061 * correctly treated as an imbalance.
10062 */
10063 env.flags |= LBF_ALL_PINNED;
10064 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
10065
10066 more_balance:
10067 rq_lock_irqsave(busiest, &rf);
10068 update_rq_clock(busiest);
10069
10070 /*
10071 * cur_ld_moved - load moved in current iteration
10072 * ld_moved - cumulative load moved across iterations
10073 */
10074 cur_ld_moved = detach_tasks(&env);
10075
10076 /*
10077 * We've detached some tasks from busiest_rq. Every
10078 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
10079 * unlock busiest->lock, and we are able to be sure
10080 * that nobody can manipulate the tasks in parallel.
10081 * See task_rq_lock() family for the details.
10082 */
10083
10084 rq_unlock(busiest, &rf);
10085
10086 if (cur_ld_moved) {
10087 attach_tasks(&env);
10088 ld_moved += cur_ld_moved;
10089 }
10090
10091 local_irq_restore(rf.flags);
10092
10093 if (env.flags & LBF_NEED_BREAK) {
10094 env.flags &= ~LBF_NEED_BREAK;
10095 goto more_balance;
10096 }
10097
10098 /*
10099 * Revisit (affine) tasks on src_cpu that couldn't be moved to
10100 * us and move them to an alternate dst_cpu in our sched_group
10101 * where they can run. The upper limit on how many times we
10102 * iterate on same src_cpu is dependent on number of CPUs in our
10103 * sched_group.
10104 *
10105 * This changes load balance semantics a bit on who can move
10106 * load to a given_cpu. In addition to the given_cpu itself
10107 * (or a ilb_cpu acting on its behalf where given_cpu is
10108 * nohz-idle), we now have balance_cpu in a position to move
10109 * load to given_cpu. In rare situations, this may cause
10110 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
10111 * _independently_ and at _same_ time to move some load to
10112 * given_cpu) causing exceess load to be moved to given_cpu.
10113 * This however should not happen so much in practice and
10114 * moreover subsequent load balance cycles should correct the
10115 * excess load moved.
10116 */
10117 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
10118
10119 /* Prevent to re-select dst_cpu via env's CPUs */
10120 __cpumask_clear_cpu(env.dst_cpu, env.cpus);
10121
10122 env.dst_rq = cpu_rq(env.new_dst_cpu);
10123 env.dst_cpu = env.new_dst_cpu;
10124 env.flags &= ~LBF_DST_PINNED;
10125 env.loop = 0;
10126 env.loop_break = sched_nr_migrate_break;
10127
10128 /*
10129 * Go back to "more_balance" rather than "redo" since we
10130 * need to continue with same src_cpu.
10131 */
10132 goto more_balance;
10133 }
10134
10135 /*
10136 * We failed to reach balance because of affinity.
10137 */
10138 if (sd_parent) {
10139 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
10140
10141 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
10142 *group_imbalance = 1;
10143 }
10144
10145 /* All tasks on this runqueue were pinned by CPU affinity */
10146 if (unlikely(env.flags & LBF_ALL_PINNED)) {
10147 __cpumask_clear_cpu(cpu_of(busiest), cpus);
10148 /*
10149 * Attempting to continue load balancing at the current
10150 * sched_domain level only makes sense if there are
10151 * active CPUs remaining as possible busiest CPUs to
10152 * pull load from which are not contained within the
10153 * destination group that is receiving any migrated
10154 * load.
10155 */
10156 if (!cpumask_subset(cpus, env.dst_grpmask)) {
10157 env.loop = 0;
10158 env.loop_break = sched_nr_migrate_break;
10159 goto redo;
10160 }
10161 goto out_all_pinned;
10162 }
10163 }
10164
10165 if (!ld_moved) {
10166 schedstat_inc(sd->lb_failed[idle]);
10167 /*
10168 * Increment the failure counter only on periodic balance.
10169 * We do not want newidle balance, which can be very
10170 * frequent, pollute the failure counter causing
10171 * excessive cache_hot migrations and active balances.
10172 */
10173 if (idle != CPU_NEWLY_IDLE)
10174 sd->nr_balance_failed++;
10175
10176 if (need_active_balance(&env)) {
10177 unsigned long flags;
10178
10179 raw_spin_lock_irqsave(&busiest->lock, flags);
10180
10181 /*
10182 * Don't kick the active_load_balance_cpu_stop,
10183 * if the curr task on busiest CPU can't be
10184 * moved to this_cpu:
10185 */
10186 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) {
10187 raw_spin_unlock_irqrestore(&busiest->lock,
10188 flags);
10189 env.flags |= LBF_ALL_PINNED;
10190 goto out_one_pinned;
10191 }
10192
10193 /*
10194 * ->active_balance synchronizes accesses to
10195 * ->active_balance_work. Once set, it's cleared
10196 * only after active load balance is finished.
10197 */
10198 if (!busiest->active_balance &&
10199 !cpu_isolated(cpu_of(busiest))) {
10200 busiest->active_balance = 1;
10201 busiest->push_cpu = this_cpu;
10202 active_balance = 1;
10203 }
10204 raw_spin_unlock_irqrestore(&busiest->lock, flags);
10205
10206 if (active_balance) {
10207 stop_one_cpu_nowait(cpu_of(busiest),
10208 active_load_balance_cpu_stop, busiest,
10209 &busiest->active_balance_work);
10210 }
10211
10212 /* We've kicked active balancing, force task migration. */
10213 sd->nr_balance_failed = sd->cache_nice_tries+1;
10214 }
10215 } else
10216 sd->nr_balance_failed = 0;
10217
10218 if (likely(!active_balance) || voluntary_active_balance(&env)) {
10219 /* We were unbalanced, so reset the balancing interval */
10220 sd->balance_interval = sd->min_interval;
10221 } else {
10222 /*
10223 * If we've begun active balancing, start to back off. This
10224 * case may not be covered by the all_pinned logic if there
10225 * is only 1 task on the busy runqueue (because we don't call
10226 * detach_tasks).
10227 */
10228 if (sd->balance_interval < sd->max_interval)
10229 sd->balance_interval *= 2;
10230 }
10231
10232 goto out;
10233
10234 out_balanced:
10235 /*
10236 * We reach balance although we may have faced some affinity
10237 * constraints. Clear the imbalance flag only if other tasks got
10238 * a chance to move and fix the imbalance.
10239 */
10240 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) {
10241 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
10242
10243 if (*group_imbalance)
10244 *group_imbalance = 0;
10245 }
10246
10247 out_all_pinned:
10248 /*
10249 * We reach balance because all tasks are pinned at this level so
10250 * we can't migrate them. Let the imbalance flag set so parent level
10251 * can try to migrate them.
10252 */
10253 schedstat_inc(sd->lb_balanced[idle]);
10254
10255 sd->nr_balance_failed = 0;
10256
10257 out_one_pinned:
10258 ld_moved = 0;
10259
10260 /*
10261 * newidle_balance() disregards balance intervals, so we could
10262 * repeatedly reach this code, which would lead to balance_interval
10263 * skyrocketting in a short amount of time. Skip the balance_interval
10264 * increase logic to avoid that.
10265 */
10266 if (env.idle == CPU_NEWLY_IDLE)
10267 goto out;
10268
10269 /* tune up the balancing interval */
10270 if ((env.flags & LBF_ALL_PINNED &&
10271 sd->balance_interval < MAX_PINNED_INTERVAL) ||
10272 sd->balance_interval < sd->max_interval)
10273 sd->balance_interval *= 2;
10274 out:
10275 return ld_moved;
10276 }
10277
10278 static inline unsigned long
get_sd_balance_interval(struct sched_domain * sd,int cpu_busy)10279 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
10280 {
10281 unsigned long interval = sd->balance_interval;
10282
10283 if (cpu_busy)
10284 interval *= sd->busy_factor;
10285
10286 /* scale ms to jiffies */
10287 interval = msecs_to_jiffies(interval);
10288
10289 /*
10290 * Reduce likelihood of busy balancing at higher domains racing with
10291 * balancing at lower domains by preventing their balancing periods
10292 * from being multiples of each other.
10293 */
10294 if (cpu_busy)
10295 interval -= 1;
10296
10297 interval = clamp(interval, 1UL, max_load_balance_interval);
10298
10299 return interval;
10300 }
10301
10302 static inline void
update_next_balance(struct sched_domain * sd,unsigned long * next_balance)10303 update_next_balance(struct sched_domain *sd, unsigned long *next_balance)
10304 {
10305 unsigned long interval, next;
10306
10307 /* used by idle balance, so cpu_busy = 0 */
10308 interval = get_sd_balance_interval(sd, 0);
10309 next = sd->last_balance + interval;
10310
10311 if (time_after(*next_balance, next))
10312 *next_balance = next;
10313 }
10314
10315 /*
10316 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes
10317 * running tasks off the busiest CPU onto idle CPUs. It requires at
10318 * least 1 task to be running on each physical CPU where possible, and
10319 * avoids physical / logical imbalances.
10320 */
active_load_balance_cpu_stop(void * data)10321 static int active_load_balance_cpu_stop(void *data)
10322 {
10323 struct rq *busiest_rq = data;
10324 int busiest_cpu = cpu_of(busiest_rq);
10325 int target_cpu = busiest_rq->push_cpu;
10326 struct rq *target_rq = cpu_rq(target_cpu);
10327 struct sched_domain *sd = NULL;
10328 struct task_struct *p = NULL;
10329 struct rq_flags rf;
10330 #ifdef CONFIG_SCHED_EAS
10331 struct task_struct *push_task;
10332 int push_task_detached = 0;
10333 #endif
10334
10335 rq_lock_irq(busiest_rq, &rf);
10336 /*
10337 * Between queueing the stop-work and running it is a hole in which
10338 * CPUs can become inactive. We should not move tasks from or to
10339 * inactive CPUs.
10340 */
10341 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu))
10342 goto out_unlock;
10343
10344 /* Make sure the requested CPU hasn't gone down in the meantime: */
10345 if (unlikely(busiest_cpu != smp_processor_id() ||
10346 !busiest_rq->active_balance))
10347 goto out_unlock;
10348
10349 /* Is there any task to move? */
10350 if (busiest_rq->nr_running <= 1)
10351 goto out_unlock;
10352
10353 /*
10354 * This condition is "impossible", if it occurs
10355 * we need to fix it. Originally reported by
10356 * Bjorn Helgaas on a 128-CPU setup.
10357 */
10358 BUG_ON(busiest_rq == target_rq);
10359
10360 #ifdef CONFIG_SCHED_EAS
10361 push_task = busiest_rq->push_task;
10362 target_cpu = busiest_rq->push_cpu;
10363 if (push_task) {
10364 struct lb_env env = {
10365 .sd = sd,
10366 .dst_cpu = target_cpu,
10367 .dst_rq = target_rq,
10368 .src_cpu = busiest_rq->cpu,
10369 .src_rq = busiest_rq,
10370 .idle = CPU_IDLE,
10371 .flags = 0,
10372 .loop = 0,
10373 };
10374 if (task_on_rq_queued(push_task) &&
10375 push_task->state == TASK_RUNNING &&
10376 task_cpu(push_task) == busiest_cpu &&
10377 cpu_online(target_cpu)) {
10378 update_rq_clock(busiest_rq);
10379 detach_task(push_task, &env);
10380 push_task_detached = 1;
10381 }
10382 goto out_unlock;
10383 }
10384 #endif
10385
10386 /* Search for an sd spanning us and the target CPU. */
10387 rcu_read_lock();
10388 for_each_domain(target_cpu, sd) {
10389 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
10390 break;
10391 }
10392
10393 if (likely(sd)) {
10394 struct lb_env env = {
10395 .sd = sd,
10396 .dst_cpu = target_cpu,
10397 .dst_rq = target_rq,
10398 .src_cpu = busiest_rq->cpu,
10399 .src_rq = busiest_rq,
10400 .idle = CPU_IDLE,
10401 /*
10402 * can_migrate_task() doesn't need to compute new_dst_cpu
10403 * for active balancing. Since we have CPU_IDLE, but no
10404 * @dst_grpmask we need to make that test go away with lying
10405 * about DST_PINNED.
10406 */
10407 .flags = LBF_DST_PINNED,
10408 };
10409
10410 schedstat_inc(sd->alb_count);
10411 update_rq_clock(busiest_rq);
10412
10413 p = detach_one_task(&env);
10414 if (p) {
10415 schedstat_inc(sd->alb_pushed);
10416 /* Active balancing done, reset the failure counter. */
10417 sd->nr_balance_failed = 0;
10418 } else {
10419 schedstat_inc(sd->alb_failed);
10420 }
10421 }
10422 rcu_read_unlock();
10423 out_unlock:
10424 busiest_rq->active_balance = 0;
10425
10426 #ifdef CONFIG_SCHED_EAS
10427 push_task = busiest_rq->push_task;
10428 if (push_task)
10429 busiest_rq->push_task = NULL;
10430 #endif
10431 rq_unlock(busiest_rq, &rf);
10432
10433 #ifdef CONFIG_SCHED_EAS
10434 if (push_task) {
10435 if (push_task_detached)
10436 attach_one_task(target_rq, push_task);
10437
10438 put_task_struct(push_task);
10439 }
10440 #endif
10441
10442 if (p)
10443 attach_one_task(target_rq, p);
10444
10445 local_irq_enable();
10446
10447 return 0;
10448 }
10449
10450 static DEFINE_SPINLOCK(balancing);
10451
10452 /*
10453 * Scale the max load_balance interval with the number of CPUs in the system.
10454 * This trades load-balance latency on larger machines for less cross talk.
10455 */
update_max_interval(void)10456 void update_max_interval(void)
10457 {
10458 unsigned int available_cpus;
10459 #ifdef CONFIG_CPU_ISOLATION_OPT
10460 cpumask_t avail_mask;
10461
10462 cpumask_andnot(&avail_mask, cpu_online_mask, cpu_isolated_mask);
10463 available_cpus = cpumask_weight(&avail_mask);
10464 #else
10465 available_cpus = num_online_cpus();
10466 #endif
10467
10468 max_load_balance_interval = HZ*available_cpus/10;
10469 }
10470
10471 /*
10472 * It checks each scheduling domain to see if it is due to be balanced,
10473 * and initiates a balancing operation if so.
10474 *
10475 * Balancing parameters are set up in init_sched_domains.
10476 */
rebalance_domains(struct rq * rq,enum cpu_idle_type idle)10477 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
10478 {
10479 int continue_balancing = 1;
10480 int cpu = rq->cpu;
10481 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
10482 unsigned long interval;
10483 struct sched_domain *sd;
10484 /* Earliest time when we have to do rebalance again */
10485 unsigned long next_balance = jiffies + 60*HZ;
10486 int update_next_balance = 0;
10487 int need_serialize, need_decay = 0;
10488 u64 max_cost = 0;
10489
10490 rcu_read_lock();
10491 for_each_domain(cpu, sd) {
10492 /*
10493 * Decay the newidle max times here because this is a regular
10494 * visit to all the domains. Decay ~1% per second.
10495 */
10496 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
10497 sd->max_newidle_lb_cost =
10498 (sd->max_newidle_lb_cost * 253) / 256;
10499 sd->next_decay_max_lb_cost = jiffies + HZ;
10500 need_decay = 1;
10501 }
10502 max_cost += sd->max_newidle_lb_cost;
10503
10504 /*
10505 * Stop the load balance at this level. There is another
10506 * CPU in our sched group which is doing load balancing more
10507 * actively.
10508 */
10509 if (!continue_balancing) {
10510 if (need_decay)
10511 continue;
10512 break;
10513 }
10514
10515 interval = get_sd_balance_interval(sd, busy);
10516
10517 need_serialize = sd->flags & SD_SERIALIZE;
10518 if (need_serialize) {
10519 if (!spin_trylock(&balancing))
10520 goto out;
10521 }
10522
10523 if (time_after_eq(jiffies, sd->last_balance + interval)) {
10524 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
10525 /*
10526 * The LBF_DST_PINNED logic could have changed
10527 * env->dst_cpu, so we can't know our idle
10528 * state even if we migrated tasks. Update it.
10529 */
10530 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
10531 busy = idle != CPU_IDLE && !sched_idle_cpu(cpu);
10532 }
10533 sd->last_balance = jiffies;
10534 interval = get_sd_balance_interval(sd, busy);
10535 }
10536 if (need_serialize)
10537 spin_unlock(&balancing);
10538 out:
10539 if (time_after(next_balance, sd->last_balance + interval)) {
10540 next_balance = sd->last_balance + interval;
10541 update_next_balance = 1;
10542 }
10543 }
10544 if (need_decay) {
10545 /*
10546 * Ensure the rq-wide value also decays but keep it at a
10547 * reasonable floor to avoid funnies with rq->avg_idle.
10548 */
10549 rq->max_idle_balance_cost =
10550 max((u64)sysctl_sched_migration_cost, max_cost);
10551 }
10552 rcu_read_unlock();
10553
10554 /*
10555 * next_balance will be updated only when there is a need.
10556 * When the cpu is attached to null domain for ex, it will not be
10557 * updated.
10558 */
10559 if (likely(update_next_balance)) {
10560 rq->next_balance = next_balance;
10561
10562 #ifdef CONFIG_NO_HZ_COMMON
10563 /*
10564 * If this CPU has been elected to perform the nohz idle
10565 * balance. Other idle CPUs have already rebalanced with
10566 * nohz_idle_balance() and nohz.next_balance has been
10567 * updated accordingly. This CPU is now running the idle load
10568 * balance for itself and we need to update the
10569 * nohz.next_balance accordingly.
10570 */
10571 if ((idle == CPU_IDLE) && time_after(nohz.next_balance, rq->next_balance))
10572 nohz.next_balance = rq->next_balance;
10573 #endif
10574 }
10575 }
10576
on_null_domain(struct rq * rq)10577 static inline int on_null_domain(struct rq *rq)
10578 {
10579 return unlikely(!rcu_dereference_sched(rq->sd));
10580 }
10581
10582 #ifdef CONFIG_NO_HZ_COMMON
10583 /*
10584 * idle load balancing details
10585 * - When one of the busy CPUs notice that there may be an idle rebalancing
10586 * needed, they will kick the idle load balancer, which then does idle
10587 * load balancing for all the idle CPUs.
10588 * - HK_FLAG_MISC CPUs are used for this task, because HK_FLAG_SCHED not set
10589 * anywhere yet.
10590 */
10591
find_new_ilb(void)10592 static inline int find_new_ilb(void)
10593 {
10594 int ilb;
10595
10596 for_each_cpu_and(ilb, nohz.idle_cpus_mask,
10597 housekeeping_cpumask(HK_FLAG_MISC)) {
10598 if (cpu_isolated(ilb))
10599 continue;
10600
10601 if (idle_cpu(ilb))
10602 return ilb;
10603 }
10604
10605 return nr_cpu_ids;
10606 }
10607
10608 /*
10609 * Kick a CPU to do the nohz balancing, if it is time for it. We pick any
10610 * idle CPU in the HK_FLAG_MISC housekeeping set (if there is one).
10611 */
kick_ilb(unsigned int flags)10612 static void kick_ilb(unsigned int flags)
10613 {
10614 int ilb_cpu;
10615
10616 /*
10617 * Increase nohz.next_balance only when if full ilb is triggered but
10618 * not if we only update stats.
10619 */
10620 if (flags & NOHZ_BALANCE_KICK)
10621 nohz.next_balance = jiffies+1;
10622
10623 ilb_cpu = find_new_ilb();
10624
10625 if (ilb_cpu >= nr_cpu_ids)
10626 return;
10627
10628 /*
10629 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets
10630 * the first flag owns it; cleared by nohz_csd_func().
10631 */
10632 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu));
10633 if (flags & NOHZ_KICK_MASK)
10634 return;
10635
10636 /*
10637 * This way we generate an IPI on the target CPU which
10638 * is idle. And the softirq performing nohz idle load balance
10639 * will be run before returning from the IPI.
10640 */
10641 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd);
10642 }
10643
10644 /*
10645 * Current decision point for kicking the idle load balancer in the presence
10646 * of idle CPUs in the system.
10647 */
nohz_balancer_kick(struct rq * rq)10648 static void nohz_balancer_kick(struct rq *rq)
10649 {
10650 unsigned long now = jiffies;
10651 struct sched_domain_shared *sds;
10652 struct sched_domain *sd;
10653 int nr_busy, i, cpu = rq->cpu;
10654 unsigned int flags = 0;
10655 cpumask_t cpumask;
10656
10657 if (unlikely(rq->idle_balance))
10658 return;
10659
10660 /*
10661 * We may be recently in ticked or tickless idle mode. At the first
10662 * busy tick after returning from idle, we will update the busy stats.
10663 */
10664 nohz_balance_exit_idle(rq);
10665
10666 /*
10667 * None are in tickless mode and hence no need for NOHZ idle load
10668 * balancing.
10669 */
10670 #ifdef CONFIG_CPU_ISOLATION_OPT
10671 cpumask_andnot(&cpumask, nohz.idle_cpus_mask, cpu_isolated_mask);
10672 if (cpumask_empty(&cpumask))
10673 return;
10674 #else
10675 cpumask_copy(&cpumask, nohz.idle_cpus_mask);
10676 if (likely(!atomic_read(&nohz.nr_cpus)))
10677 return;
10678 #endif
10679
10680 if (READ_ONCE(nohz.has_blocked) &&
10681 time_after(now, READ_ONCE(nohz.next_blocked)))
10682 flags = NOHZ_STATS_KICK;
10683
10684 if (time_before(now, nohz.next_balance))
10685 goto out;
10686
10687 if (rq->nr_running >= 2) {
10688 flags = NOHZ_KICK_MASK;
10689 goto out;
10690 }
10691
10692 rcu_read_lock();
10693
10694 sd = rcu_dereference(rq->sd);
10695 if (sd) {
10696 /*
10697 * If there's a CFS task and the current CPU has reduced
10698 * capacity; kick the ILB to see if there's a better CPU to run
10699 * on.
10700 */
10701 if (rq->cfs.h_nr_running >= 1 && check_cpu_capacity(rq, sd)) {
10702 flags = NOHZ_KICK_MASK;
10703 goto unlock;
10704 }
10705 }
10706
10707 sd = rcu_dereference(per_cpu(sd_asym_packing, cpu));
10708 if (sd) {
10709 /*
10710 * When ASYM_PACKING; see if there's a more preferred CPU
10711 * currently idle; in which case, kick the ILB to move tasks
10712 * around.
10713 */
10714 for_each_cpu_and(i, sched_domain_span(sd), &cpumask) {
10715 if (sched_asym_prefer(i, cpu)) {
10716 flags = NOHZ_KICK_MASK;
10717 goto unlock;
10718 }
10719 }
10720 }
10721
10722 sd = rcu_dereference(per_cpu(sd_asym_cpucapacity, cpu));
10723 if (sd) {
10724 /*
10725 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU
10726 * to run the misfit task on.
10727 */
10728 if (check_misfit_status(rq, sd)) {
10729 flags = NOHZ_KICK_MASK;
10730 goto unlock;
10731 }
10732
10733 /*
10734 * For asymmetric systems, we do not want to nicely balance
10735 * cache use, instead we want to embrace asymmetry and only
10736 * ensure tasks have enough CPU capacity.
10737 *
10738 * Skip the LLC logic because it's not relevant in that case.
10739 */
10740 goto unlock;
10741 }
10742
10743 sds = rcu_dereference(per_cpu(sd_llc_shared, cpu));
10744 if (sds) {
10745 /*
10746 * If there is an imbalance between LLC domains (IOW we could
10747 * increase the overall cache use), we need some less-loaded LLC
10748 * domain to pull some load. Likewise, we may need to spread
10749 * load within the current LLC domain (e.g. packed SMT cores but
10750 * other CPUs are idle). We can't really know from here how busy
10751 * the others are - so just get a nohz balance going if it looks
10752 * like this LLC domain has tasks we could move.
10753 */
10754 nr_busy = atomic_read(&sds->nr_busy_cpus);
10755 if (nr_busy > 1) {
10756 flags = NOHZ_KICK_MASK;
10757 goto unlock;
10758 }
10759 }
10760 unlock:
10761 rcu_read_unlock();
10762 out:
10763 if (flags)
10764 kick_ilb(flags);
10765 }
10766
set_cpu_sd_state_busy(int cpu)10767 static void set_cpu_sd_state_busy(int cpu)
10768 {
10769 struct sched_domain *sd;
10770
10771 rcu_read_lock();
10772 sd = rcu_dereference(per_cpu(sd_llc, cpu));
10773
10774 if (!sd || !sd->nohz_idle)
10775 goto unlock;
10776 sd->nohz_idle = 0;
10777
10778 atomic_inc(&sd->shared->nr_busy_cpus);
10779 unlock:
10780 rcu_read_unlock();
10781 }
10782
nohz_balance_exit_idle(struct rq * rq)10783 void nohz_balance_exit_idle(struct rq *rq)
10784 {
10785 SCHED_WARN_ON(rq != this_rq());
10786
10787 if (likely(!rq->nohz_tick_stopped))
10788 return;
10789
10790 rq->nohz_tick_stopped = 0;
10791 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask);
10792 atomic_dec(&nohz.nr_cpus);
10793
10794 set_cpu_sd_state_busy(rq->cpu);
10795 }
10796
set_cpu_sd_state_idle(int cpu)10797 static void set_cpu_sd_state_idle(int cpu)
10798 {
10799 struct sched_domain *sd;
10800
10801 rcu_read_lock();
10802 sd = rcu_dereference(per_cpu(sd_llc, cpu));
10803
10804 if (!sd || sd->nohz_idle)
10805 goto unlock;
10806 sd->nohz_idle = 1;
10807
10808 atomic_dec(&sd->shared->nr_busy_cpus);
10809 unlock:
10810 rcu_read_unlock();
10811 }
10812
10813 /*
10814 * This routine will record that the CPU is going idle with tick stopped.
10815 * This info will be used in performing idle load balancing in the future.
10816 */
nohz_balance_enter_idle(int cpu)10817 void nohz_balance_enter_idle(int cpu)
10818 {
10819 struct rq *rq = cpu_rq(cpu);
10820
10821 SCHED_WARN_ON(cpu != smp_processor_id());
10822
10823 /* If this CPU is going down, then nothing needs to be done: */
10824 if (!cpu_active(cpu))
10825 return;
10826
10827 /* Spare idle load balancing on CPUs that don't want to be disturbed: */
10828 if (!housekeeping_cpu(cpu, HK_FLAG_SCHED))
10829 return;
10830
10831 /*
10832 * Can be set safely without rq->lock held
10833 * If a clear happens, it will have evaluated last additions because
10834 * rq->lock is held during the check and the clear
10835 */
10836 rq->has_blocked_load = 1;
10837
10838 /*
10839 * The tick is still stopped but load could have been added in the
10840 * meantime. We set the nohz.has_blocked flag to trig a check of the
10841 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear
10842 * of nohz.has_blocked can only happen after checking the new load
10843 */
10844 if (rq->nohz_tick_stopped)
10845 goto out;
10846
10847 /* If we're a completely isolated CPU, we don't play: */
10848 if (on_null_domain(rq))
10849 return;
10850
10851 rq->nohz_tick_stopped = 1;
10852
10853 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
10854 atomic_inc(&nohz.nr_cpus);
10855
10856 /*
10857 * Ensures that if nohz_idle_balance() fails to observe our
10858 * @idle_cpus_mask store, it must observe the @has_blocked
10859 * store.
10860 */
10861 smp_mb__after_atomic();
10862
10863 set_cpu_sd_state_idle(cpu);
10864
10865 out:
10866 /*
10867 * Each time a cpu enter idle, we assume that it has blocked load and
10868 * enable the periodic update of the load of idle cpus
10869 */
10870 WRITE_ONCE(nohz.has_blocked, 1);
10871 }
10872
10873 /*
10874 * Internal function that runs load balance for all idle cpus. The load balance
10875 * can be a simple update of blocked load or a complete load balance with
10876 * tasks movement depending of flags.
10877 * The function returns false if the loop has stopped before running
10878 * through all idle CPUs.
10879 */
_nohz_idle_balance(struct rq * this_rq,unsigned int flags,enum cpu_idle_type idle)10880 static bool _nohz_idle_balance(struct rq *this_rq, unsigned int flags,
10881 enum cpu_idle_type idle)
10882 {
10883 /* Earliest time when we have to do rebalance again */
10884 unsigned long now = jiffies;
10885 unsigned long next_balance = now + 60*HZ;
10886 bool has_blocked_load = false;
10887 int update_next_balance = 0;
10888 int this_cpu = this_rq->cpu;
10889 int balance_cpu;
10890 int ret = false;
10891 struct rq *rq;
10892 cpumask_t cpus;
10893
10894 SCHED_WARN_ON((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK);
10895
10896 /*
10897 * We assume there will be no idle load after this update and clear
10898 * the has_blocked flag. If a cpu enters idle in the mean time, it will
10899 * set the has_blocked flag and trig another update of idle load.
10900 * Because a cpu that becomes idle, is added to idle_cpus_mask before
10901 * setting the flag, we are sure to not clear the state and not
10902 * check the load of an idle cpu.
10903 */
10904 WRITE_ONCE(nohz.has_blocked, 0);
10905
10906 /*
10907 * Ensures that if we miss the CPU, we must see the has_blocked
10908 * store from nohz_balance_enter_idle().
10909 */
10910 smp_mb();
10911
10912 #ifdef CONFIG_CPU_ISOLATION_OPT
10913 cpumask_andnot(&cpus, nohz.idle_cpus_mask, cpu_isolated_mask);
10914 #else
10915 cpumask_copy(&cpus, nohz.idle_cpus_mask);
10916 #endif
10917
10918 for_each_cpu(balance_cpu, &cpus) {
10919 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
10920 continue;
10921
10922 /*
10923 * If this CPU gets work to do, stop the load balancing
10924 * work being done for other CPUs. Next load
10925 * balancing owner will pick it up.
10926 */
10927 if (need_resched()) {
10928 has_blocked_load = true;
10929 goto abort;
10930 }
10931
10932 rq = cpu_rq(balance_cpu);
10933
10934 has_blocked_load |= update_nohz_stats(rq, true);
10935
10936 /*
10937 * If time for next balance is due,
10938 * do the balance.
10939 */
10940 if (time_after_eq(jiffies, rq->next_balance)) {
10941 struct rq_flags rf;
10942
10943 rq_lock_irqsave(rq, &rf);
10944 update_rq_clock(rq);
10945 rq_unlock_irqrestore(rq, &rf);
10946
10947 if (flags & NOHZ_BALANCE_KICK)
10948 rebalance_domains(rq, CPU_IDLE);
10949 }
10950
10951 if (time_after(next_balance, rq->next_balance)) {
10952 next_balance = rq->next_balance;
10953 update_next_balance = 1;
10954 }
10955 }
10956
10957 /*
10958 * next_balance will be updated only when there is a need.
10959 * When the CPU is attached to null domain for ex, it will not be
10960 * updated.
10961 */
10962 if (likely(update_next_balance))
10963 nohz.next_balance = next_balance;
10964
10965 /* Newly idle CPU doesn't need an update */
10966 if (idle != CPU_NEWLY_IDLE) {
10967 update_blocked_averages(this_cpu);
10968 has_blocked_load |= this_rq->has_blocked_load;
10969 }
10970
10971 if (flags & NOHZ_BALANCE_KICK)
10972 rebalance_domains(this_rq, CPU_IDLE);
10973
10974 WRITE_ONCE(nohz.next_blocked,
10975 now + msecs_to_jiffies(LOAD_AVG_PERIOD));
10976
10977 /* The full idle balance loop has been done */
10978 ret = true;
10979
10980 abort:
10981 /* There is still blocked load, enable periodic update */
10982 if (has_blocked_load)
10983 WRITE_ONCE(nohz.has_blocked, 1);
10984
10985 return ret;
10986 }
10987
10988 /*
10989 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
10990 * rebalancing for all the cpus for whom scheduler ticks are stopped.
10991 */
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)10992 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
10993 {
10994 unsigned int flags = this_rq->nohz_idle_balance;
10995
10996 if (!flags)
10997 return false;
10998
10999 this_rq->nohz_idle_balance = 0;
11000
11001 if (idle != CPU_IDLE)
11002 return false;
11003
11004 _nohz_idle_balance(this_rq, flags, idle);
11005
11006 return true;
11007 }
11008
nohz_newidle_balance(struct rq * this_rq)11009 static void nohz_newidle_balance(struct rq *this_rq)
11010 {
11011 int this_cpu = this_rq->cpu;
11012
11013 /*
11014 * This CPU doesn't want to be disturbed by scheduler
11015 * housekeeping
11016 */
11017 if (!housekeeping_cpu(this_cpu, HK_FLAG_SCHED))
11018 return;
11019
11020 /* Will wake up very soon. No time for doing anything else*/
11021 if (this_rq->avg_idle < sysctl_sched_migration_cost)
11022 return;
11023
11024 /* Don't need to update blocked load of idle CPUs*/
11025 if (!READ_ONCE(nohz.has_blocked) ||
11026 time_before(jiffies, READ_ONCE(nohz.next_blocked)))
11027 return;
11028
11029 raw_spin_unlock(&this_rq->lock);
11030 /*
11031 * This CPU is going to be idle and blocked load of idle CPUs
11032 * need to be updated. Run the ilb locally as it is a good
11033 * candidate for ilb instead of waking up another idle CPU.
11034 * Kick an normal ilb if we failed to do the update.
11035 */
11036 if (!_nohz_idle_balance(this_rq, NOHZ_STATS_KICK, CPU_NEWLY_IDLE))
11037 kick_ilb(NOHZ_STATS_KICK);
11038 raw_spin_lock(&this_rq->lock);
11039 }
11040
11041 #else /* !CONFIG_NO_HZ_COMMON */
nohz_balancer_kick(struct rq * rq)11042 static inline void nohz_balancer_kick(struct rq *rq) { }
11043
nohz_idle_balance(struct rq * this_rq,enum cpu_idle_type idle)11044 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
11045 {
11046 return false;
11047 }
11048
nohz_newidle_balance(struct rq * this_rq)11049 static inline void nohz_newidle_balance(struct rq *this_rq) { }
11050 #endif /* CONFIG_NO_HZ_COMMON */
11051
11052 /*
11053 * idle_balance is called by schedule() if this_cpu is about to become
11054 * idle. Attempts to pull tasks from other CPUs.
11055 *
11056 * Returns:
11057 * < 0 - we released the lock and there are !fair tasks present
11058 * 0 - failed, no new tasks
11059 * > 0 - success, new (fair) tasks present
11060 */
newidle_balance(struct rq * this_rq,struct rq_flags * rf)11061 static int newidle_balance(struct rq *this_rq, struct rq_flags *rf)
11062 {
11063 unsigned long next_balance = jiffies + HZ;
11064 int this_cpu = this_rq->cpu;
11065 struct sched_domain *sd;
11066 int pulled_task = 0;
11067 u64 curr_cost = 0;
11068
11069 if (cpu_isolated(this_cpu))
11070 return 0;
11071
11072 update_misfit_status(NULL, this_rq);
11073 /*
11074 * We must set idle_stamp _before_ calling idle_balance(), such that we
11075 * measure the duration of idle_balance() as idle time.
11076 */
11077 this_rq->idle_stamp = rq_clock(this_rq);
11078
11079 /*
11080 * Do not pull tasks towards !active CPUs...
11081 */
11082 if (!cpu_active(this_cpu))
11083 return 0;
11084
11085 /*
11086 * This is OK, because current is on_cpu, which avoids it being picked
11087 * for load-balance and preemption/IRQs are still disabled avoiding
11088 * further scheduler activity on it and we're being very careful to
11089 * re-start the picking loop.
11090 */
11091 rq_unpin_lock(this_rq, rf);
11092
11093 if (this_rq->avg_idle < sysctl_sched_migration_cost ||
11094 !READ_ONCE(this_rq->rd->overload)) {
11095
11096 rcu_read_lock();
11097 sd = rcu_dereference_check_sched_domain(this_rq->sd);
11098 if (sd)
11099 update_next_balance(sd, &next_balance);
11100 rcu_read_unlock();
11101
11102 nohz_newidle_balance(this_rq);
11103
11104 goto out;
11105 }
11106
11107 raw_spin_unlock(&this_rq->lock);
11108
11109 update_blocked_averages(this_cpu);
11110 rcu_read_lock();
11111 for_each_domain(this_cpu, sd) {
11112 int continue_balancing = 1;
11113 u64 t0, domain_cost;
11114
11115 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
11116 update_next_balance(sd, &next_balance);
11117 break;
11118 }
11119
11120 if (sd->flags & SD_BALANCE_NEWIDLE) {
11121 t0 = sched_clock_cpu(this_cpu);
11122
11123 pulled_task = load_balance(this_cpu, this_rq,
11124 sd, CPU_NEWLY_IDLE,
11125 &continue_balancing);
11126
11127 domain_cost = sched_clock_cpu(this_cpu) - t0;
11128 if (domain_cost > sd->max_newidle_lb_cost)
11129 sd->max_newidle_lb_cost = domain_cost;
11130
11131 curr_cost += domain_cost;
11132 }
11133
11134 update_next_balance(sd, &next_balance);
11135
11136 /*
11137 * Stop searching for tasks to pull if there are
11138 * now runnable tasks on this rq.
11139 */
11140 if (pulled_task || this_rq->nr_running > 0)
11141 break;
11142 }
11143 rcu_read_unlock();
11144
11145 raw_spin_lock(&this_rq->lock);
11146
11147 if (curr_cost > this_rq->max_idle_balance_cost)
11148 this_rq->max_idle_balance_cost = curr_cost;
11149
11150 out:
11151 /*
11152 * While browsing the domains, we released the rq lock, a task could
11153 * have been enqueued in the meantime. Since we're not going idle,
11154 * pretend we pulled a task.
11155 */
11156 if (this_rq->cfs.h_nr_running && !pulled_task)
11157 pulled_task = 1;
11158
11159 /* Move the next balance forward */
11160 if (time_after(this_rq->next_balance, next_balance))
11161 this_rq->next_balance = next_balance;
11162
11163 /* Is there a task of a high priority class? */
11164 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
11165 pulled_task = -1;
11166
11167 if (pulled_task)
11168 this_rq->idle_stamp = 0;
11169
11170 rq_repin_lock(this_rq, rf);
11171
11172 return pulled_task;
11173 }
11174
11175 /*
11176 * run_rebalance_domains is triggered when needed from the scheduler tick.
11177 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
11178 */
run_rebalance_domains(struct softirq_action * h)11179 static __latent_entropy void run_rebalance_domains(struct softirq_action *h)
11180 {
11181 struct rq *this_rq = this_rq();
11182 enum cpu_idle_type idle = this_rq->idle_balance ?
11183 CPU_IDLE : CPU_NOT_IDLE;
11184
11185 /*
11186 * Since core isolation doesn't update nohz.idle_cpus_mask, there
11187 * is a possibility this nohz kicked cpu could be isolated. Hence
11188 * return if the cpu is isolated.
11189 */
11190 if (cpu_isolated(this_rq->cpu))
11191 return;
11192
11193 /*
11194 * If this CPU has a pending nohz_balance_kick, then do the
11195 * balancing on behalf of the other idle CPUs whose ticks are
11196 * stopped. Do nohz_idle_balance *before* rebalance_domains to
11197 * give the idle CPUs a chance to load balance. Else we may
11198 * load balance only within the local sched_domain hierarchy
11199 * and abort nohz_idle_balance altogether if we pull some load.
11200 */
11201 if (nohz_idle_balance(this_rq, idle))
11202 return;
11203
11204 /* normal load balance */
11205 update_blocked_averages(this_rq->cpu);
11206 rebalance_domains(this_rq, idle);
11207 }
11208
11209 /*
11210 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
11211 */
trigger_load_balance(struct rq * rq)11212 void trigger_load_balance(struct rq *rq)
11213 {
11214 /* Don't need to rebalance while attached to NULL domain or
11215 * cpu is isolated.
11216 */
11217 if (unlikely(on_null_domain(rq)) || cpu_isolated(cpu_of(rq)))
11218 return;
11219
11220 if (time_after_eq(jiffies, rq->next_balance))
11221 raise_softirq(SCHED_SOFTIRQ);
11222
11223 nohz_balancer_kick(rq);
11224 }
11225
rq_online_fair(struct rq * rq)11226 static void rq_online_fair(struct rq *rq)
11227 {
11228 update_sysctl();
11229
11230 update_runtime_enabled(rq);
11231 }
11232
rq_offline_fair(struct rq * rq)11233 static void rq_offline_fair(struct rq *rq)
11234 {
11235 update_sysctl();
11236
11237 /* Ensure any throttled groups are reachable by pick_next_task */
11238 unthrottle_offline_cfs_rqs(rq);
11239 }
11240
11241 #ifdef CONFIG_SCHED_EAS
11242 static inline int
kick_active_balance(struct rq * rq,struct task_struct * p,int new_cpu)11243 kick_active_balance(struct rq *rq, struct task_struct *p, int new_cpu)
11244 {
11245 unsigned long flags;
11246 int rc = 0;
11247
11248 if (cpu_of(rq) == new_cpu)
11249 return rc;
11250
11251 /* Invoke active balance to force migrate currently running task */
11252 raw_spin_lock_irqsave(&rq->lock, flags);
11253 if (!rq->active_balance) {
11254 rq->active_balance = 1;
11255 rq->push_cpu = new_cpu;
11256 get_task_struct(p);
11257 rq->push_task = p;
11258 rc = 1;
11259 }
11260 raw_spin_unlock_irqrestore(&rq->lock, flags);
11261 return rc;
11262 }
11263
11264 DEFINE_RAW_SPINLOCK(migration_lock);
check_for_migration_fair(struct rq * rq,struct task_struct * p)11265 static void check_for_migration_fair(struct rq *rq, struct task_struct *p)
11266 {
11267 int active_balance;
11268 int new_cpu = -1;
11269 int prev_cpu = task_cpu(p);
11270 int ret;
11271
11272 #ifdef CONFIG_SCHED_RTG
11273 bool need_down_migrate = false;
11274 struct cpumask *rtg_target = find_rtg_target(p);
11275
11276 if (rtg_target &&
11277 (capacity_orig_of(prev_cpu) >
11278 capacity_orig_of(cpumask_first(rtg_target))))
11279 need_down_migrate = true;
11280 #endif
11281
11282 if (rq->misfit_task_load) {
11283 if (rq->curr->state != TASK_RUNNING ||
11284 rq->curr->nr_cpus_allowed == 1)
11285 return;
11286
11287 raw_spin_lock(&migration_lock);
11288 #ifdef CONFIG_SCHED_RTG
11289 if (rtg_target) {
11290 new_cpu = find_rtg_cpu(p);
11291
11292 if (new_cpu != -1 && need_down_migrate &&
11293 cpumask_test_cpu(new_cpu, rtg_target) &&
11294 idle_cpu(new_cpu))
11295 goto do_active_balance;
11296
11297 if (new_cpu != -1 &&
11298 capacity_orig_of(new_cpu) > capacity_orig_of(prev_cpu))
11299 goto do_active_balance;
11300
11301 goto out_unlock;
11302 }
11303 #endif
11304 rcu_read_lock();
11305 new_cpu = find_energy_efficient_cpu(p, prev_cpu);
11306 rcu_read_unlock();
11307
11308 if (new_cpu == -1 ||
11309 capacity_orig_of(new_cpu) <= capacity_orig_of(prev_cpu))
11310 goto out_unlock;
11311 #ifdef CONFIG_SCHED_RTG
11312 do_active_balance:
11313 #endif
11314 active_balance = kick_active_balance(rq, p, new_cpu);
11315 if (active_balance) {
11316 mark_reserved(new_cpu);
11317 raw_spin_unlock(&migration_lock);
11318 ret = stop_one_cpu_nowait(prev_cpu,
11319 active_load_balance_cpu_stop, rq,
11320 &rq->active_balance_work);
11321 if (!ret)
11322 clear_reserved(new_cpu);
11323 else
11324 wake_up_if_idle(new_cpu);
11325 return;
11326 }
11327 out_unlock:
11328 raw_spin_unlock(&migration_lock);
11329 }
11330 }
11331 #endif /* CONFIG_SCHED_EAS */
11332 #endif /* CONFIG_SMP */
11333
11334 /*
11335 * scheduler tick hitting a task of our scheduling class.
11336 *
11337 * NOTE: This function can be called remotely by the tick offload that
11338 * goes along full dynticks. Therefore no local assumption can be made
11339 * and everything must be accessed through the @rq and @curr passed in
11340 * parameters.
11341 */
task_tick_fair(struct rq * rq,struct task_struct * curr,int queued)11342 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
11343 {
11344 struct cfs_rq *cfs_rq;
11345 struct sched_entity *se = &curr->se;
11346
11347 for_each_sched_entity(se) {
11348 cfs_rq = cfs_rq_of(se);
11349 entity_tick(cfs_rq, se, queued);
11350 }
11351
11352 if (static_branch_unlikely(&sched_numa_balancing))
11353 task_tick_numa(rq, curr);
11354
11355 update_misfit_status(curr, rq);
11356 update_overutilized_status(task_rq(curr));
11357 }
11358
11359 /*
11360 * called on fork with the child task as argument from the parent's context
11361 * - child not yet on the tasklist
11362 * - preemption disabled
11363 */
task_fork_fair(struct task_struct * p)11364 static void task_fork_fair(struct task_struct *p)
11365 {
11366 struct cfs_rq *cfs_rq;
11367 struct sched_entity *se = &p->se, *curr;
11368 struct rq *rq = this_rq();
11369 struct rq_flags rf;
11370
11371 rq_lock(rq, &rf);
11372 update_rq_clock(rq);
11373
11374 cfs_rq = task_cfs_rq(current);
11375 curr = cfs_rq->curr;
11376 if (curr) {
11377 update_curr(cfs_rq);
11378 se->vruntime = curr->vruntime;
11379 }
11380 place_entity(cfs_rq, se, 1);
11381
11382 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
11383 /*
11384 * Upon rescheduling, sched_class::put_prev_task() will place
11385 * 'current' within the tree based on its new key value.
11386 */
11387 swap(curr->vruntime, se->vruntime);
11388 resched_curr(rq);
11389 }
11390
11391 se->vruntime -= cfs_rq->min_vruntime;
11392 rq_unlock(rq, &rf);
11393 }
11394
11395 /*
11396 * Priority of the task has changed. Check to see if we preempt
11397 * the current task.
11398 */
11399 static void
prio_changed_fair(struct rq * rq,struct task_struct * p,int oldprio)11400 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
11401 {
11402 if (!task_on_rq_queued(p))
11403 return;
11404
11405 if (rq->cfs.nr_running == 1)
11406 return;
11407
11408 /*
11409 * Reschedule if we are currently running on this runqueue and
11410 * our priority decreased, or if we are not currently running on
11411 * this runqueue and our priority is higher than the current's
11412 */
11413 if (rq->curr == p) {
11414 if (p->prio > oldprio)
11415 resched_curr(rq);
11416 } else
11417 check_preempt_curr(rq, p, 0);
11418 }
11419
vruntime_normalized(struct task_struct * p)11420 static inline bool vruntime_normalized(struct task_struct *p)
11421 {
11422 struct sched_entity *se = &p->se;
11423
11424 /*
11425 * In both the TASK_ON_RQ_QUEUED and TASK_ON_RQ_MIGRATING cases,
11426 * the dequeue_entity(.flags=0) will already have normalized the
11427 * vruntime.
11428 */
11429 if (p->on_rq)
11430 return true;
11431
11432 /*
11433 * When !on_rq, vruntime of the task has usually NOT been normalized.
11434 * But there are some cases where it has already been normalized:
11435 *
11436 * - A forked child which is waiting for being woken up by
11437 * wake_up_new_task().
11438 * - A task which has been woken up by try_to_wake_up() and
11439 * waiting for actually being woken up by sched_ttwu_pending().
11440 */
11441 if (!se->sum_exec_runtime ||
11442 (p->state == TASK_WAKING && p->sched_remote_wakeup))
11443 return true;
11444
11445 return false;
11446 }
11447
11448 #ifdef CONFIG_FAIR_GROUP_SCHED
11449 /*
11450 * Propagate the changes of the sched_entity across the tg tree to make it
11451 * visible to the root
11452 */
propagate_entity_cfs_rq(struct sched_entity * se)11453 static void propagate_entity_cfs_rq(struct sched_entity *se)
11454 {
11455 struct cfs_rq *cfs_rq;
11456
11457 list_add_leaf_cfs_rq(cfs_rq_of(se));
11458
11459 /* Start to propagate at parent */
11460 se = se->parent;
11461
11462 for_each_sched_entity(se) {
11463 cfs_rq = cfs_rq_of(se);
11464
11465 if (!cfs_rq_throttled(cfs_rq)){
11466 update_load_avg(cfs_rq, se, UPDATE_TG);
11467 list_add_leaf_cfs_rq(cfs_rq);
11468 continue;
11469 }
11470
11471 if (list_add_leaf_cfs_rq(cfs_rq))
11472 break;
11473 }
11474 }
11475 #else
propagate_entity_cfs_rq(struct sched_entity * se)11476 static void propagate_entity_cfs_rq(struct sched_entity *se) { }
11477 #endif
11478
detach_entity_cfs_rq(struct sched_entity * se)11479 static void detach_entity_cfs_rq(struct sched_entity *se)
11480 {
11481 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11482
11483 /* Catch up with the cfs_rq and remove our load when we leave */
11484 update_load_avg(cfs_rq, se, 0);
11485 detach_entity_load_avg(cfs_rq, se);
11486 update_tg_load_avg(cfs_rq);
11487 propagate_entity_cfs_rq(se);
11488 }
11489
attach_entity_cfs_rq(struct sched_entity * se)11490 static void attach_entity_cfs_rq(struct sched_entity *se)
11491 {
11492 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11493
11494 #ifdef CONFIG_FAIR_GROUP_SCHED
11495 /*
11496 * Since the real-depth could have been changed (only FAIR
11497 * class maintain depth value), reset depth properly.
11498 */
11499 se->depth = se->parent ? se->parent->depth + 1 : 0;
11500 #endif
11501
11502 /* Synchronize entity with its cfs_rq */
11503 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD);
11504 attach_entity_load_avg(cfs_rq, se);
11505 update_tg_load_avg(cfs_rq);
11506 propagate_entity_cfs_rq(se);
11507 }
11508
detach_task_cfs_rq(struct task_struct * p)11509 static void detach_task_cfs_rq(struct task_struct *p)
11510 {
11511 struct sched_entity *se = &p->se;
11512 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11513
11514 if (!vruntime_normalized(p)) {
11515 /*
11516 * Fix up our vruntime so that the current sleep doesn't
11517 * cause 'unlimited' sleep bonus.
11518 */
11519 place_entity(cfs_rq, se, 0);
11520 se->vruntime -= cfs_rq->min_vruntime;
11521 }
11522
11523 detach_entity_cfs_rq(se);
11524 }
11525
attach_task_cfs_rq(struct task_struct * p)11526 static void attach_task_cfs_rq(struct task_struct *p)
11527 {
11528 struct sched_entity *se = &p->se;
11529 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11530
11531 attach_entity_cfs_rq(se);
11532
11533 if (!vruntime_normalized(p))
11534 se->vruntime += cfs_rq->min_vruntime;
11535 }
11536
switched_from_fair(struct rq * rq,struct task_struct * p)11537 static void switched_from_fair(struct rq *rq, struct task_struct *p)
11538 {
11539 detach_task_cfs_rq(p);
11540 }
11541
switched_to_fair(struct rq * rq,struct task_struct * p)11542 static void switched_to_fair(struct rq *rq, struct task_struct *p)
11543 {
11544 attach_task_cfs_rq(p);
11545
11546 if (task_on_rq_queued(p)) {
11547 /*
11548 * We were most likely switched from sched_rt, so
11549 * kick off the schedule if running, otherwise just see
11550 * if we can still preempt the current task.
11551 */
11552 if (rq->curr == p)
11553 resched_curr(rq);
11554 else
11555 check_preempt_curr(rq, p, 0);
11556 }
11557 }
11558
11559 /* Account for a task changing its policy or group.
11560 *
11561 * This routine is mostly called to set cfs_rq->curr field when a task
11562 * migrates between groups/classes.
11563 */
set_next_task_fair(struct rq * rq,struct task_struct * p,bool first)11564 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first)
11565 {
11566 struct sched_entity *se = &p->se;
11567
11568 #ifdef CONFIG_SMP
11569 if (task_on_rq_queued(p)) {
11570 /*
11571 * Move the next running task to the front of the list, so our
11572 * cfs_tasks list becomes MRU one.
11573 */
11574 list_move(&se->group_node, &rq->cfs_tasks);
11575 }
11576 #endif
11577
11578 for_each_sched_entity(se) {
11579 struct cfs_rq *cfs_rq = cfs_rq_of(se);
11580
11581 set_next_entity(cfs_rq, se);
11582 /* ensure bandwidth has been allocated on our new cfs_rq */
11583 account_cfs_rq_runtime(cfs_rq, 0);
11584 }
11585 }
11586
init_cfs_rq(struct cfs_rq * cfs_rq)11587 void init_cfs_rq(struct cfs_rq *cfs_rq)
11588 {
11589 cfs_rq->tasks_timeline = RB_ROOT_CACHED;
11590 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
11591 #ifndef CONFIG_64BIT
11592 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
11593 #endif
11594 #ifdef CONFIG_SMP
11595 raw_spin_lock_init(&cfs_rq->removed.lock);
11596 #endif
11597 }
11598
11599 #ifdef CONFIG_FAIR_GROUP_SCHED
task_set_group_fair(struct task_struct * p)11600 static void task_set_group_fair(struct task_struct *p)
11601 {
11602 struct sched_entity *se = &p->se;
11603
11604 set_task_rq(p, task_cpu(p));
11605 se->depth = se->parent ? se->parent->depth + 1 : 0;
11606 }
11607
task_move_group_fair(struct task_struct * p)11608 static void task_move_group_fair(struct task_struct *p)
11609 {
11610 detach_task_cfs_rq(p);
11611 set_task_rq(p, task_cpu(p));
11612
11613 #ifdef CONFIG_SMP
11614 /* Tell se's cfs_rq has been changed -- migrated */
11615 p->se.avg.last_update_time = 0;
11616 #endif
11617 attach_task_cfs_rq(p);
11618 }
11619
task_change_group_fair(struct task_struct * p,int type)11620 static void task_change_group_fair(struct task_struct *p, int type)
11621 {
11622 switch (type) {
11623 case TASK_SET_GROUP:
11624 task_set_group_fair(p);
11625 break;
11626
11627 case TASK_MOVE_GROUP:
11628 task_move_group_fair(p);
11629 break;
11630 }
11631 }
11632
free_fair_sched_group(struct task_group * tg)11633 void free_fair_sched_group(struct task_group *tg)
11634 {
11635 int i;
11636
11637 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
11638
11639 for_each_possible_cpu(i) {
11640 if (tg->cfs_rq)
11641 kfree(tg->cfs_rq[i]);
11642 if (tg->se)
11643 kfree(tg->se[i]);
11644 }
11645
11646 kfree(tg->cfs_rq);
11647 kfree(tg->se);
11648 }
11649
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)11650 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11651 {
11652 struct sched_entity *se;
11653 struct cfs_rq *cfs_rq;
11654 int i;
11655
11656 tg->cfs_rq = kcalloc(nr_cpu_ids, sizeof(cfs_rq), GFP_KERNEL);
11657 if (!tg->cfs_rq)
11658 goto err;
11659 tg->se = kcalloc(nr_cpu_ids, sizeof(se), GFP_KERNEL);
11660 if (!tg->se)
11661 goto err;
11662
11663 tg->shares = NICE_0_LOAD;
11664
11665 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
11666
11667 for_each_possible_cpu(i) {
11668 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
11669 GFP_KERNEL, cpu_to_node(i));
11670 if (!cfs_rq)
11671 goto err;
11672
11673 se = kzalloc_node(sizeof(struct sched_entity),
11674 GFP_KERNEL, cpu_to_node(i));
11675 if (!se)
11676 goto err_free_rq;
11677
11678 init_cfs_rq(cfs_rq);
11679 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
11680 init_entity_runnable_average(se);
11681 }
11682
11683 return 1;
11684
11685 err_free_rq:
11686 kfree(cfs_rq);
11687 err:
11688 return 0;
11689 }
11690
online_fair_sched_group(struct task_group * tg)11691 void online_fair_sched_group(struct task_group *tg)
11692 {
11693 struct sched_entity *se;
11694 struct rq_flags rf;
11695 struct rq *rq;
11696 int i;
11697
11698 for_each_possible_cpu(i) {
11699 rq = cpu_rq(i);
11700 se = tg->se[i];
11701 rq_lock_irq(rq, &rf);
11702 update_rq_clock(rq);
11703 attach_entity_cfs_rq(se);
11704 sync_throttle(tg, i);
11705 rq_unlock_irq(rq, &rf);
11706 }
11707 }
11708
unregister_fair_sched_group(struct task_group * tg)11709 void unregister_fair_sched_group(struct task_group *tg)
11710 {
11711 unsigned long flags;
11712 struct rq *rq;
11713 int cpu;
11714
11715 for_each_possible_cpu(cpu) {
11716 if (tg->se[cpu])
11717 remove_entity_load_avg(tg->se[cpu]);
11718
11719 /*
11720 * Only empty task groups can be destroyed; so we can speculatively
11721 * check on_list without danger of it being re-added.
11722 */
11723 if (!tg->cfs_rq[cpu]->on_list)
11724 continue;
11725
11726 rq = cpu_rq(cpu);
11727
11728 raw_spin_lock_irqsave(&rq->lock, flags);
11729 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
11730 raw_spin_unlock_irqrestore(&rq->lock, flags);
11731 }
11732 }
11733
init_tg_cfs_entry(struct task_group * tg,struct cfs_rq * cfs_rq,struct sched_entity * se,int cpu,struct sched_entity * parent)11734 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
11735 struct sched_entity *se, int cpu,
11736 struct sched_entity *parent)
11737 {
11738 struct rq *rq = cpu_rq(cpu);
11739
11740 cfs_rq->tg = tg;
11741 cfs_rq->rq = rq;
11742 init_cfs_rq_runtime(cfs_rq);
11743
11744 tg->cfs_rq[cpu] = cfs_rq;
11745 tg->se[cpu] = se;
11746
11747 /* se could be NULL for root_task_group */
11748 if (!se)
11749 return;
11750
11751 if (!parent) {
11752 se->cfs_rq = &rq->cfs;
11753 se->depth = 0;
11754 } else {
11755 se->cfs_rq = parent->my_q;
11756 se->depth = parent->depth + 1;
11757 }
11758
11759 se->my_q = cfs_rq;
11760 /* guarantee group entities always have weight */
11761 update_load_set(&se->load, NICE_0_LOAD);
11762 se->parent = parent;
11763 }
11764
11765 static DEFINE_MUTEX(shares_mutex);
11766
sched_group_set_shares(struct task_group * tg,unsigned long shares)11767 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
11768 {
11769 int i;
11770
11771 /*
11772 * We can't change the weight of the root cgroup.
11773 */
11774 if (!tg->se[0])
11775 return -EINVAL;
11776
11777 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
11778
11779 mutex_lock(&shares_mutex);
11780 if (tg->shares == shares)
11781 goto done;
11782
11783 tg->shares = shares;
11784 for_each_possible_cpu(i) {
11785 struct rq *rq = cpu_rq(i);
11786 struct sched_entity *se = tg->se[i];
11787 struct rq_flags rf;
11788
11789 /* Propagate contribution to hierarchy */
11790 rq_lock_irqsave(rq, &rf);
11791 update_rq_clock(rq);
11792 for_each_sched_entity(se) {
11793 update_load_avg(cfs_rq_of(se), se, UPDATE_TG);
11794 update_cfs_group(se);
11795 }
11796 rq_unlock_irqrestore(rq, &rf);
11797 }
11798
11799 done:
11800 mutex_unlock(&shares_mutex);
11801 return 0;
11802 }
11803 #else /* CONFIG_FAIR_GROUP_SCHED */
11804
free_fair_sched_group(struct task_group * tg)11805 void free_fair_sched_group(struct task_group *tg) { }
11806
alloc_fair_sched_group(struct task_group * tg,struct task_group * parent)11807 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
11808 {
11809 return 1;
11810 }
11811
online_fair_sched_group(struct task_group * tg)11812 void online_fair_sched_group(struct task_group *tg) { }
11813
unregister_fair_sched_group(struct task_group * tg)11814 void unregister_fair_sched_group(struct task_group *tg) { }
11815
11816 #endif /* CONFIG_FAIR_GROUP_SCHED */
11817
11818
get_rr_interval_fair(struct rq * rq,struct task_struct * task)11819 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
11820 {
11821 struct sched_entity *se = &task->se;
11822 unsigned int rr_interval = 0;
11823
11824 /*
11825 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
11826 * idle runqueue:
11827 */
11828 if (rq->cfs.load.weight)
11829 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
11830
11831 return rr_interval;
11832 }
11833
11834 /*
11835 * All the scheduling class methods:
11836 */
11837 const struct sched_class fair_sched_class
11838 __section("__fair_sched_class") = {
11839 .enqueue_task = enqueue_task_fair,
11840 .dequeue_task = dequeue_task_fair,
11841 .yield_task = yield_task_fair,
11842 .yield_to_task = yield_to_task_fair,
11843
11844 .check_preempt_curr = check_preempt_wakeup,
11845
11846 .pick_next_task = __pick_next_task_fair,
11847 .put_prev_task = put_prev_task_fair,
11848 .set_next_task = set_next_task_fair,
11849
11850 #ifdef CONFIG_SMP
11851 .balance = balance_fair,
11852 .select_task_rq = select_task_rq_fair,
11853 .migrate_task_rq = migrate_task_rq_fair,
11854
11855 .rq_online = rq_online_fair,
11856 .rq_offline = rq_offline_fair,
11857
11858 .task_dead = task_dead_fair,
11859 .set_cpus_allowed = set_cpus_allowed_common,
11860 #endif
11861
11862 .task_tick = task_tick_fair,
11863 .task_fork = task_fork_fair,
11864
11865 .prio_changed = prio_changed_fair,
11866 .switched_from = switched_from_fair,
11867 .switched_to = switched_to_fair,
11868
11869 .get_rr_interval = get_rr_interval_fair,
11870
11871 .update_curr = update_curr_fair,
11872
11873 #ifdef CONFIG_FAIR_GROUP_SCHED
11874 .task_change_group = task_change_group_fair,
11875 #endif
11876
11877 #ifdef CONFIG_UCLAMP_TASK
11878 .uclamp_enabled = 1,
11879 #endif
11880 #ifdef CONFIG_SCHED_WALT
11881 .fixup_walt_sched_stats = walt_fixup_sched_stats_fair,
11882 #endif
11883 #ifdef CONFIG_SCHED_EAS
11884 .check_for_migration = check_for_migration_fair,
11885 #endif
11886 };
11887
11888 #ifdef CONFIG_SCHED_DEBUG
print_cfs_stats(struct seq_file * m,int cpu)11889 void print_cfs_stats(struct seq_file *m, int cpu)
11890 {
11891 struct cfs_rq *cfs_rq, *pos;
11892
11893 rcu_read_lock();
11894 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos)
11895 print_cfs_rq(m, cpu, cfs_rq);
11896 rcu_read_unlock();
11897 }
11898
11899 #ifdef CONFIG_NUMA_BALANCING
show_numa_stats(struct task_struct * p,struct seq_file * m)11900 void show_numa_stats(struct task_struct *p, struct seq_file *m)
11901 {
11902 int node;
11903 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0;
11904 struct numa_group *ng;
11905
11906 rcu_read_lock();
11907 ng = rcu_dereference(p->numa_group);
11908 for_each_online_node(node) {
11909 if (p->numa_faults) {
11910 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)];
11911 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)];
11912 }
11913 if (ng) {
11914 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)],
11915 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)];
11916 }
11917 print_numa_stats(m, node, tsf, tpf, gsf, gpf);
11918 }
11919 rcu_read_unlock();
11920 }
11921 #endif /* CONFIG_NUMA_BALANCING */
11922 #endif /* CONFIG_SCHED_DEBUG */
11923
init_sched_fair_class(void)11924 __init void init_sched_fair_class(void)
11925 {
11926 #ifdef CONFIG_SMP
11927 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
11928
11929 #ifdef CONFIG_NO_HZ_COMMON
11930 nohz.next_balance = jiffies;
11931 nohz.next_blocked = jiffies;
11932 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
11933 #endif
11934 #endif /* SMP */
11935
11936 }
11937
11938 /* WALT sched implementation begins here */
11939 #ifdef CONFIG_SCHED_WALT
11940
11941 #ifdef CONFIG_CFS_BANDWIDTH
11942
walt_init_cfs_rq_stats(struct cfs_rq * cfs_rq)11943 static void walt_init_cfs_rq_stats(struct cfs_rq *cfs_rq)
11944 {
11945 cfs_rq->walt_stats.cumulative_runnable_avg_scaled = 0;
11946 }
11947
walt_inc_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)11948 static void walt_inc_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p)
11949 {
11950 fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
11951 p->ravg.demand_scaled);
11952 }
11953
walt_dec_cfs_rq_stats(struct cfs_rq * cfs_rq,struct task_struct * p)11954 static void walt_dec_cfs_rq_stats(struct cfs_rq *cfs_rq, struct task_struct *p)
11955 {
11956 fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
11957 -(s64)p->ravg.demand_scaled);
11958 }
11959
walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats * stats,struct cfs_rq * tcfs_rq)11960 static void walt_inc_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
11961 struct cfs_rq *tcfs_rq)
11962 {
11963 struct rq *rq = rq_of(tcfs_rq);
11964
11965 fixup_cumulative_runnable_avg(stats,
11966 tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11967
11968 if (stats == &rq->walt_stats)
11969 walt_fixup_cum_window_demand(rq,
11970 tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11971
11972 }
11973
walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats * stats,struct cfs_rq * tcfs_rq)11974 static void walt_dec_throttled_cfs_rq_stats(struct walt_sched_stats *stats,
11975 struct cfs_rq *tcfs_rq)
11976 {
11977 struct rq *rq = rq_of(tcfs_rq);
11978
11979 fixup_cumulative_runnable_avg(stats,
11980 -tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11981
11982 /*
11983 * We remove the throttled cfs_rq's tasks's contribution from the
11984 * cumulative window demand so that the same can be added
11985 * unconditionally when the cfs_rq is unthrottled.
11986 */
11987 if (stats == &rq->walt_stats)
11988 walt_fixup_cum_window_demand(rq,
11989 -tcfs_rq->walt_stats.cumulative_runnable_avg_scaled);
11990 }
11991
walt_fixup_sched_stats_fair(struct rq * rq,struct task_struct * p,u16 updated_demand_scaled)11992 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
11993 u16 updated_demand_scaled)
11994 {
11995 struct cfs_rq *cfs_rq;
11996 struct sched_entity *se = &p->se;
11997 s64 task_load_delta = (s64)updated_demand_scaled -
11998 p->ravg.demand_scaled;
11999
12000 for_each_sched_entity(se) {
12001 cfs_rq = cfs_rq_of(se);
12002
12003 fixup_cumulative_runnable_avg(&cfs_rq->walt_stats,
12004 task_load_delta);
12005 if (cfs_rq_throttled(cfs_rq))
12006 break;
12007 }
12008
12009 /* Fix up rq->walt_stats only if we didn't find any throttled cfs_rq */
12010 if (!se) {
12011 fixup_cumulative_runnable_avg(&rq->walt_stats,
12012 task_load_delta);
12013 walt_fixup_cum_window_demand(rq, task_load_delta);
12014 }
12015 }
12016
12017 #else /* CONFIG_CFS_BANDWIDTH */
walt_fixup_sched_stats_fair(struct rq * rq,struct task_struct * p,u16 updated_demand_scaled)12018 static void walt_fixup_sched_stats_fair(struct rq *rq, struct task_struct *p,
12019 u16 updated_demand_scaled)
12020 {
12021 fixup_walt_sched_stats_common(rq, p, updated_demand_scaled);
12022 }
12023 #endif /* CONFIG_CFS_BANDWIDTH */
12024 #endif /* CONFIG_SCHED_WALT */
12025
12026 /*
12027 * Helper functions to facilitate extracting info from tracepoints.
12028 */
12029
sched_trace_cfs_rq_avg(struct cfs_rq * cfs_rq)12030 const struct sched_avg *sched_trace_cfs_rq_avg(struct cfs_rq *cfs_rq)
12031 {
12032 #ifdef CONFIG_SMP
12033 return cfs_rq ? &cfs_rq->avg : NULL;
12034 #else
12035 return NULL;
12036 #endif
12037 }
12038 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_avg);
12039
sched_trace_cfs_rq_path(struct cfs_rq * cfs_rq,char * str,int len)12040 char *sched_trace_cfs_rq_path(struct cfs_rq *cfs_rq, char *str, int len)
12041 {
12042 if (!cfs_rq) {
12043 if (str)
12044 strlcpy(str, "(null)", len);
12045 else
12046 return NULL;
12047 }
12048
12049 cfs_rq_tg_path(cfs_rq, str, len);
12050 return str;
12051 }
12052 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_path);
12053
sched_trace_cfs_rq_cpu(struct cfs_rq * cfs_rq)12054 int sched_trace_cfs_rq_cpu(struct cfs_rq *cfs_rq)
12055 {
12056 return cfs_rq ? cpu_of(rq_of(cfs_rq)) : -1;
12057 }
12058 EXPORT_SYMBOL_GPL(sched_trace_cfs_rq_cpu);
12059
sched_trace_rq_avg_rt(struct rq * rq)12060 const struct sched_avg *sched_trace_rq_avg_rt(struct rq *rq)
12061 {
12062 #ifdef CONFIG_SMP
12063 return rq ? &rq->avg_rt : NULL;
12064 #else
12065 return NULL;
12066 #endif
12067 }
12068 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_rt);
12069
sched_trace_rq_avg_dl(struct rq * rq)12070 const struct sched_avg *sched_trace_rq_avg_dl(struct rq *rq)
12071 {
12072 #ifdef CONFIG_SMP
12073 return rq ? &rq->avg_dl : NULL;
12074 #else
12075 return NULL;
12076 #endif
12077 }
12078 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_dl);
12079
sched_trace_rq_avg_irq(struct rq * rq)12080 const struct sched_avg *sched_trace_rq_avg_irq(struct rq *rq)
12081 {
12082 #if defined(CONFIG_SMP) && defined(CONFIG_HAVE_SCHED_AVG_IRQ)
12083 return rq ? &rq->avg_irq : NULL;
12084 #else
12085 return NULL;
12086 #endif
12087 }
12088 EXPORT_SYMBOL_GPL(sched_trace_rq_avg_irq);
12089
sched_trace_rq_cpu(struct rq * rq)12090 int sched_trace_rq_cpu(struct rq *rq)
12091 {
12092 return rq ? cpu_of(rq) : -1;
12093 }
12094 EXPORT_SYMBOL_GPL(sched_trace_rq_cpu);
12095
sched_trace_rq_cpu_capacity(struct rq * rq)12096 int sched_trace_rq_cpu_capacity(struct rq *rq)
12097 {
12098 return rq ?
12099 #ifdef CONFIG_SMP
12100 rq->cpu_capacity
12101 #else
12102 SCHED_CAPACITY_SCALE
12103 #endif
12104 : -1;
12105 }
12106 EXPORT_SYMBOL_GPL(sched_trace_rq_cpu_capacity);
12107
sched_trace_rd_span(struct root_domain * rd)12108 const struct cpumask *sched_trace_rd_span(struct root_domain *rd)
12109 {
12110 #ifdef CONFIG_SMP
12111 return rd ? rd->span : NULL;
12112 #else
12113 return NULL;
12114 #endif
12115 }
12116 EXPORT_SYMBOL_GPL(sched_trace_rd_span);
12117
sched_trace_rq_nr_running(struct rq * rq)12118 int sched_trace_rq_nr_running(struct rq *rq)
12119 {
12120 return rq ? rq->nr_running : -1;
12121 }
12122 EXPORT_SYMBOL_GPL(sched_trace_rq_nr_running);
12123