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