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