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